1、利用绝对定位和margin
此方法的原理说将左右两侧进行定位,让其脱离文档流。 中心区域自然流动到它们下面,再为其设置margin值
此方法页面元素结构可以顺序可以随意变动,注意top值需要进行处理,不然可能会出现对不齐现象
HTML
- <div id='container'>
- <div class='left'>左侧</div>
- <div class='center'>中间</div>
- <div class='right'>右侧</div>
- </div>
CSS
- #container {
- position: relative;
- }
- .left, .right{
- position: absolute;
- top: 0;
- width: 200px;
- min-height: 500px;
- background-color: red;
- }
- .left {
- left: 0;
- }
- .right {
- right: 0;
- }
- .center {
- margin: 0px 210px;
- min-height: 500px;
- background-color: yellow;
- }
2、利用浮动和margin
此方法的原理说将左右两侧进行float 浮动让其脱离文档流,中心部分处于正常文档流,再为其设置margin值
此方法一定要将center中间部分放到最后,当窗口特别小时右侧会被挤下来
HTML
- <div id='container'>
- <div class='left'>左侧</div>
- <div class='right'>右侧</div>
- <div class='center'>中间</div>
- </div>
CSS
- #container {
- position: relative;
- }
- .left, .right {
- width: 200px;
- min-height: 500px;
- background-color: red;
- }
- .left {
- float: left;
- }
- .right {
- float: right;
- }
- .center {
- min-height: 500px;
- margin: 0px 210px;
- background-color: yellow;
- }
3、圣杯布局
此方法最常见,三者相互关联,最稳健。
首先需要将中间部分放再最前面,外面用一层容器包裹。外层容器让其占满整个屏幕100%, 左中右三者都float: left。 将center左右margin设置为两边容器的宽度加上边距,将left左侧margin-left设置为-100%,让其出现在最左侧,将right右侧margin-right设置为-200px,让其出现在最右侧。
HTML
- <div id='container'>
- <div class='center_wrap'>
- <div class='center'>中间</div>
- </div>
- <div class='left'>左侧</div>
- <div class='right'>右侧</div>
- </div>
CSS
- #container {
- position: relative;
- }
- .center_wrap, .left, .right{
- float: left;
- min-height: 500px;
- }
- .center_wrap {
- width: 100%;
- }
- .center_wrap .center{
- min-height: 500px;
- margin: 0px 210px;
- background-color: yellow;
- }
- .left, .right {
- width: 200px;
- background-color: red;
- }
- .left {
- margin-left: -100%;
- }
- .right {
- margin-left: -200px;
- }
4、CSS3 flex
HTML
- <div id='container'>
- <div class='left'>左侧</div>
- <div class='center'>中间</div>
- <div class='right'>右侧</div>
- </div>
CSS
- #container {
- width: 100%;
- display: flex;
- }
- .left, .right {
- width: 200px;
- background-color: red;
- min-height: 500px;
- }
- .center {
- flex: 1;
- min-height: 500px;
- margin: 0 10px;
- background-color: yellow;
- }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持w3xue。