CSS 三栏布局(圣杯布局与双飞翼布局)
三栏布局的概念:三列从左到右,依次排列,左边区域和右边区域固定宽,而中间内容区域宽度自适应。
圣杯布局: 1.浮动 2.margin负值
HTML
<div class="werppar">
<div class="container"></div>
<div class="left"></div>
<div class="right"></div>
</div>
CSS
*{
margin: 0;
padding: 0;
}
.werppar{
background-color: pink;
/*左右栏通过添加负的margin放到正确的位置了,此段代码是为了摆正中间栏的位置*/
padding:0 200px;
}
.container,.left,.right{
float: left;
height: 200px;
}
.container{
width:100%;
height:200px;
background:blue;
}
.left{
width:200px;
height:200px;
/*margin负值,让移动父级容器的宽度*/
margin-left:-100%;
background:#f40;
/*中间栏的位置摆正之后,左栏的位置也相应右移,通过相对定位的left恢复到正确位置*/
position:relative;
left:-200px;
}
.right{
width:200px;
height:200px;
margin-left:-200px;
background:#0c9;
/*中间栏的位置摆正之后,右栏的位置也相应左移,通过相对定位的right恢复到正确位置*/
position:relative;
right:-200px;
}
双飞翼布局:双飞翼布局其实是根据圣杯布局演化出来的一种布局
HTML
<div class="werppar">
<div class="box">
<div class="container"></div>
</div>
<div class="left"></div>
<div class="right"></div>
<p style="clear: both;"></p>
</div>
CSS
.werppar{
width:100%;
}
.box,.left,.right{
float: left;
height: 200px;
}
.box{
width:100%;
height:200px;
}
.container{
margin : 0 200px;
height: 200px;
background:blue;
}
.left{
width:200px;
height:200px;
margin-left:-100%;
background:#f40;
}
.right{
width:200px;
height:200px;
margin-left:-200px;
background:#0c9;
}
在这里我们可以看出结构发生了改变,我们的内容区域使用一个.box的元素包裹起来了,而且浮动的再也不是.container元素了,这也就是说,container元素不会被外面的浮动元素所影响了
其次我们可以发现,这里的left:-100%就能回到想要的位置?这是为什么呢,需要注意的一点是,在这里。left父级盒子是宽度100%的,不再是圣杯布局中留出来左右padding值的父级自适应宽度的盒子
那么同理了,right盒子也是因为这样,所以直接margin-left:-200px正好贴到父级盒子最右边,就能得到想要的位置了