今天在某论坛看到一个题目,觉得很有意思,下面我们就来看问题:
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
.box1, .box2, .box3 {
width: 200px;
height:40px;
}
.box1, .box3{
margin: 20px;
}
.box2 {
margin:40px 20px;
}
基于这三个Div,添加CSS,做出一列有5个Div的效果,并且背景色依次为蓝色,黄色,红色,黄色,蓝色。
第一感觉就是借用伪元素来实现,于是就写出来了下面代码:
.box1,.box2,.box3{
width: 200px;
height: 20px;
}
.box1,.box3{
position: relative;
background: blue;
margin: 0 auto;
}
.box2{
background: red;
margin: 20px auto;
}
.box1:after{
content: "";
width: 200px;
height: 20px;
display: block;
background: yellow;
margin: 0px auto;
position: absolute;
left: 0px;
top: 20px;
}
.box3:before{
content: "";
width: 200px;
height: 20px;
display: block;
background: yellow;
margin: 0px auto;
position: absolute;
left: 0px;
top: -20px;
}
但是一想,这个不符合道理啊其实,我们添加的伪元素是不会干扰现有的html结构的啊,但是我添加的这俩个伪元素,实际上严格上并不能满足这个观念啊,于是想到了另外一种方法,那就是margin塌陷。
.box1, .box2, .box3 {
width: 200px;
}
.box1{
height: 200px;
background: blue;
margin-bottom: -160px;
}
.box2{
height: 120px;
margin-bottom: -80px;
background: yellow
}
.box3{
height: 40px;
background: red;
}
这个代码貌似更加符合题目要求,下面我们来解释一下什么叫做margin补偿,margin决定元素最终的边界,也就是说我将我的box1的margin-bottom
向上提了-160px,所以box2上边界就从box1的下边界处开始,以此可以想象出box3的变化,所以使用这种方式就可以轻易的达到我们想要的情况。