垂直外边距的重叠
如有以下代码片段:
<!--结构-->
<div class="box1"></div>
<div class="box2"></div>
/**样式**/
box1 {
width: 100px;
height: 100px;
background-color: red;
/*为红色的盒子设置一个下外边距*/
margin-bottom: 100px;
}
box2 {
width: 100px;
height: 100px;
background-color: green;
}
其效果如图-1所示
若将样式设置为
box1 {
width: 100px;
height: 100px;
background-color: red;
/*为红色的盒子设置一个下外边距*/
margin-bottom: 100px;
}
box2 {
width: 100px;
height: 100px;
background-color: green;
/*为绿色的盒子设置一个上外边距*/
margin-bottom: 100px;
}
其效果如图-2所示,与图-1完全相同
若将结构改为
<!-- 结构 -->
<div class="box1"></div>
a
<div class="box2"></div>
其效果如图-3所示
这个现象称为垂直外边距的重叠。
在网页中,相邻的垂直方向的外边距会发生外边距的重叠,所谓的外边距重叠是指兄弟元素之间的相邻外边距会取最大值而不是取和。
又有以下代码片段:
<!-- 结构 -->
<div class="box3">
<div class="box4"></div>
</div>
/**样式**/
.box3 {
width: 200px;
height: 200px;
background-color: yellow;
}
.box4 {
width: 100px;
height: 100px;
background-color: yellowgreen;
/*
* 为子元素设置一个上外边距,即子元素的位置下移
*/
margin-top: 100px;
}
其效果如图-4所示
如果父子元素的垂直外边距相邻了,则子元素的外边距会设置给父元素。
我们解决垂直外边距的重叠带来的问题时,必须从“相邻”和“垂直”着手去思考解决方法。
例如用另一个元素或border
将两个外边距隔开,使其不再相邻,即可解决该问题。
还可以改用其他样式来代替margin
,不使用垂直外边距。
如发现错误请联系我,谢谢你。
本文链接:http://ninefire.tk/HTML&CSS.basics/36.html