圣杯布局
圣杯布局是一种常见的CSS布局,它要求:
- 底部和顶部各自占领屏幕的全部宽度
- 上下部之间是一个三栏布局
- 三栏布局两侧宽度不变,中间部分自动填充整个区域
- 中间部分的高度是三栏中高度最高区域的高度
下面介绍两种实现方式:
浮动实现
<style>
.header,.footer{
height: 200px;
width: 100%;
background: #f40;
}
.footer{
clear:both;
}
.container{
padding-left:200px;//这个就是左边盒子将来的宽度
padding-right:300px;//这个就是右边盒子将来的宽度
}
.container div{
float: left;
position: relative;//将所有的盒子设为相对定位
}
.mid{
width: 100%;
background: yellow;
}
.left{
width: 200px;
background: skyblue;
margin-left: -100%;//很关键,margin-left:-100%是按照父盒子的宽度来计算的
left:-200px;//很关键
}
.right{
width: 300px;
background: cyan;
margin-right:-300px;//很关键
}
</style>
<div class="header">这里是头部</div>
<div class="container">
<div class="mid">中间部分</div>
<div class="left">左边</div>
<div class="right">右边</div>
</div>
<div class="footer">这里是底部</div>
flex弹性布局实现
弹性布局就是给外面的container盒子设置display:flex;然后左右固定宽度,中间的盒子设置flex:1即可。
双飞翼布局
双飞翼布局是在middle的div里又插入一个div,通过调整内部div的margin值,实现中间栏自适应,内容写到内部div中
<style>
.hd{
height:50px;
background: #666;
text-align: center;
}
.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;
}
.footer{
clear:both; /*记得清楚浮动*/
height:50px;
background: #666;
text-align: center;
}
</style>
<div class="hd">header</div>
<div class="middle">
<div class="inside">middle</div>
</div>
<div class="left">left</div>
<div class="right">right</div>
<div class="footer">footer</div>