1、利用内外间距相抵消,为父元素设置overflow:hidden;实现
步骤:
(1)每一列使用padding-bottom值撑开背景色
(2)每一列使用padding撑开的多余的占位让margin负值抵消;
(3)父级盒设置溢出隐藏
优点:结构简单,兼容所有浏览器
缺点:伪等高,需要合理控制margin和padding值,扩展性较差
理解:
个人觉得是由padding-bottom值将盒子撑大,继而由margin-bottom将底边线挪回盒子本来的底部,这样设置overflow:hidden时能够
将padding-bottom撑大的背景隐藏起来,当内容变多时,内容较少的列展示的其实是padding-bottom的背景
代码:
<style>
.clearfix{
*zoom: 1;
}
.clearfix::after{
content: "";
display: block;
clear: both;
}
.wrap{
width: 1000px;
margin: 0 auto;
overflow: hidden;
}
.wrap>div{
min-height: 50px;
}
.wrap .left{
width: 200px;
background: lightblue;
float: left;
padding-bottom: 10000px;
margin-bottom: -10000px;
}
.wrap .center{
width: 500px;
background: lightcoral;
float: left;
padding-bottom: 10000px;
margin-bottom: -10000px;
}
.wrap .right{
width: 300px;
background: lightgreen;
float: left;
padding-bottom: 10000px;
margin-bottom: -10000px;
}
</style>
<body>
<div class="wrap clearfix">
<div class="left">左盒子</div>
<div class="center">中间盒子</div>
<div class="right">右盒子</div>
</div>
</body>
2、利用内容撑开父元素的特点实现
步骤:
(1)有几列就进行几个div嵌套,这几个div负责背景的显示,负责内容的那几列div盒子放在最内侧的div盒子中
(2)通过相对定位,为那几列的背景分配位置
(3)通过margin负值,将内容移到对应的背景的位置
(4)父元素设置溢出隐藏(最外层盒子指定width时要设置,否则挤出去的背景会显示)
优缺点:扩展性好,可以实现自适应,结构嵌套复杂
代码:
<style>
.wrap{
overflow: hidden;
}
.clearfix{
*zoom: 1;
}
.clearfix::after{
content: "";
display: block;
clear: both;
}
.fl{
float: left;
}
.wrap .con1{
width: 100%;
background: rebeccapurple;
}
.wrap .con2{
width: 100%;
background: rosybrown;
position: relative;
left: 20%;
}
.wrap .con3{
width: 100%;
background: skyblue;
position: relative;
left: 60%;
}
.wrap .con3>div{
min-height: 100px;
}
.wrap .con3 .left{
width: 20%;
margin-left: -80%;
}
.wrap .con3 .center{
width: 60%;
margin-left: -60%;
}
.wrap .con3 .right{
width: 20%;
}
</style>
<body>
<div class="wrap">
<div class="con1">
<div class="con2">
<div class="con3 clearfix">
<div class="left fl">左侧盒子</div>
<div class="center fl">中间盒子</div>
<div class="right fl">右侧盒子</div>
</div>
</div>
</div>
</div>
</body>
3、利用边框模拟背景,实现等高的显示效果
步骤:
(1)左边框、右边框、背景颜色分别对应三列的背景颜色;
(2)通过margin值,同步列的位置
特点:扩展性差,超过三列的布局不适用
代码:
<style>
.clearfix{
*zoom: 1;
}
.clearfix::after{
content: "";
display: block;
clear: both;
}
.fl{
float: left;
}
.wrap{
width: 600px;
border-left: 200px solid cornflowerblue;
border-right: 200px solid pink;
background: plum;
margin: 0 auto;
}
.wrap>div{
min-height: 200px;
}
.wrap .left{
width: 200px;
margin-left: -200px;
}
.wrap .center{
width: 600px;
}
.wrap .right{
width: 200px;
margin-right: -200px;
}
</style>
<body>
<div class="wrap clearfix">
<div class="left fl">左侧盒子</div>
<div class="center fl">中间盒子</div>
<div class="right fl">右侧盒子</div>
</div>
</body>