在实际开发中,左右两侧固定宽度,中间自适应的三列布局是经常能够遇到的,尤其是最近的一个项目中,属于微信公众号,移动端的网页。在部分页面中,就需要用到这种布局,我是采用flex布局来搞定的。为了总结一下相关的知识,特意在网上收集了几篇相关的文章。
这种布局,主要是通过两类技术原理来实现的:
- 基于margin来实现;
- 基于CSS3中的弹性布局flex属性来实现;
绝对定位的方法
这种方法,其实原理很简单。就是将左右两侧使用绝对定位,这样二者脱离了文档流,中间的部分则设置margin就好了。
HTML片段
<div class="wrap">
<div class="left"></div>
<div class="center"></div>
<div class="right"></div>
</div>
CSS片段
* {
margin: 0;
padding: 0;
}
.wrap {
width: 100%;
height: 100px;
position: relative;
}
.left {
width: 200px;
height: 100px;
position: absolute;
left: 0;
top: 0;
background-color: blue;
}
.right {
width: 200px;
height: 100px;
position: absolute;
right: 0;
top: 0;
background-color: blue;
}
.center {
height: 100px;
background-color: red;
margin: 0 200px;
}
浮动的方法
浮动法的原理其实跟绝对定位相似的,就是使用对左右使用分别使用float:left和float:right,从而使左右两个元素脱离文档流,中间元素正常在正常文档流中,使用margin指定左右外边距对其进行一个定位。
需要注意的是:center块要写在左右两侧的后面,不然,不在一行。
HTML片段
<div class="left"></div>
<div class="right"></div>
<div class="center"></div>
CSS片段
.left {
float: left;
width: 200px;
height: 100px;
background-color: blue;
}
.right {
float: right;
width: 200px;
height: 100px;
background-color: yellow;
}
.center {
margin: 0 200px;
height: 100px;
background-color: red;
}
圣杯布局
圣杯布局的的原理是利用margin的负值的特性来实现的。主要步骤如下:
- 在center块外层添加一个div,并设置左浮,以及宽度(这个宽度要与left块的margin-left相匹配),center块设置左右的margin,margin-left要与left块的宽度相等,margin-right要与right块的宽度相等。
- left块设置左浮,并且其margin-left设置成负值,这个负值与center块外层的div的宽度相等,这样,left块就移动到center的左侧了。
- right块设置左浮,并且其margin-left设置成负值,这个负值与自身宽度相等,这样,right块就移动到center的右侧了。
代码如下:
HTML片段
<div id="wrap">
<div id="center">center</div>
</div>
<div id="left_margin">left</div>
<div id="right_margin">right</div>
CSS片段
#wrap {
width: 100%;
height: 100px;
background-color: gray;
float: left;
}
#center {
margin: 0 200px;/*关键步骤:在#center的左右两侧空出#left_margin和#right_margin的宽度来*/
height: 100px;
background-color: red;
}
#left_margin{
float: left;
width: 200px;
height: 100px;
background-color: blue;
margin-left: -100%; /*关键步骤:能够让#left_margin块从第二行移动到左侧*/
}
#right_margin {
float: left;
width: 200px;
height: 100px;
background-color: yellow;
margin-left: -200px;/*关键步骤:能够让#right_margin块从第二行移动到右侧*/
}
这个布局非常常用,需要注意的是,布局中间部分一定要放在前面,左右顺序不限制。对于left快的margin负值一定要等于wrap的宽度。
flex布局
在外围包裹一层div,设置为display:flex;center块设置flex:1,不设置宽度,left和right块设置固定的宽度。
HTML片段
<div class="wrap">
<div class="left"></div>
<div class="center"></div>
<div class="right"></div>
</div>
CSS片段
.wrap {
display: flex;
width: 100%;
height: 100px;
}
.left,.right {
width: 200px;
height: 100px;
background-color: blue;
}
.center {
flex: 1;
height: 100px;
background-color: red;
}