两边固定中间自适应布局的方法
1.使用弹性布局flex,左右两边设置宽度,中间使用flex:1填充;
html部分:
<div id="box"> <div id="left">left</div> <div id="center">center</div> <div id="right">right</div> </div>
css部分:
#box{
width:100%;
height:100px;
display:flex;
margin:10px;
}
#left,#right{
width:200px;
height:100px;
margin:10px;
background-color:#999;
}
#center{
flex:1;
height:100px;
margin:10px;/*左右margin不会叠加*/
background-color:#f00;
}
2.position定位,左右固定,中间自适应 利用绝对定位
html部分:
<div class="container"> <div class="left">left</div> <div class="center">center</div> <div class="right">right</div> </div>
css部分:
.container{
width: 100%;
height: 100%;
position: relative;
}
.left{
position: absolute;
left: 0;
top: 0;
width: 400px;
height: 200px;
background-color: black;
color:#fff;
}
.center{
/*width: auto;*/ /*如果没有这一句,那么,center这个div的文字就不会自动换行*/
margin: 0 400px;
height: 400px;
background-color: yellow;
}
.right{
position: absolute;
top: 0;
right: 0;
width: 400px;
height: 300px;
background-color: red;
}
3.float浮动定位,让左右元素浮动,缺点是中间元素必须置于二者之后,不然right元素会进入下一行
html部分:
<div id="box">
<div id="left">left</div>
<div id="right">right</div>
<div id="center">center</div>
</div>
css部分:
.left,.right{ width:200px; height:200px; background-color:#999; } .left{ float:left; } .right{ float:right; } .center{ margin:0 200px; height:300px; background-color:#f00; }
4.圣杯布局,父元素设置左右两边padding空白给左右两个子元素,3个子元素全部浮动
html部分:(注意midd写在前面)
<div id="bd"> <div id="middle">middle</div> <div id="left">left</div> <div id="right">right</div> </div>
css部分:
#bd{ /*左右栏通过添加负的margin放到正确的位置了,此段代码是为了摆正中间栏的位置*/ padding:0 200px 0 180px; height:100px; } #middle{ float:left; width:100%;/*左栏上去到第一行*/ height:100px; background:blue; } #left{ float:left; width:180px; height:100px; margin-left:-100%; background:#0c9; /*中间栏的位置摆正之后,左栏的位置也相应右移,通过相对定位的left恢复到正确位置*/ position:relative; left:-180px; } #right{ float:left; width:200px; height:100px; margin-left:-200px; background:#0c9; /*中间栏的位置摆正之后,右栏的位置也相应左移,通过相对定位的right恢复到正确位置*/ position:relative; right:-200px; }
5.双飞翼布局
html部分:
<div id="middle"> <div id="inside">middle</div> </div> <div id="left">left</div> <div id="right">right</div>
css部分:
#middle{ float:left; width:100%;/*左栏上去到第一行*/ height:100px; background:blue; } #left{ float:left; width:180px; height:100px; margin-left:-100%; background:#0c9; } #right{ float:left; width:200px; height:100px; margin-left:-200px; background:#0c9; } /*给内部div添加margin,把内容放到中间栏,其实整个背景还是100%*/ #inside{ margin:0 200px 0 180px; height:100px; }

浙公网安备 33010602011771号