当两个垂直外边距相遇时,这两个外边距会合并为一个外边距,叠加之后的外边距高度等于发生叠加之前的两个外边距的最大值。
- 水平外边距永远不会有叠加,margin-left,margin-right;
- 垂直外边距叠加会且只会发生在:同级元素、父子元素和空元素;
- 外边距叠加针对的是block以及inline-块元素,不包括inline元素,因为inline元素margin-top/margin-bottom不生效
<div style="height:100px;background-color:red;margin-bottom:10px;">
我是红色块
</div>
<div style="height:100px;background-color:blue;margin-top:20px;">
我是蓝色块,我和红色块的垂直距离是max(10px,20px)=20px
</div>
<div style="height:100px;background-color:red;margin-bottom:10px;">
我是红色块
</div>
<div style="height:100px;background-color:blue;margin-top:-70px;">
我是蓝色块,我要上移,遮住一部分的红色
</div>
负margin使用场景
- 图片与文字对齐
图片与文字排在一起往往是不对齐的,因为他们默认是基线对齐(vertical-align: baseline),实现对齐可以使用(vertical-align:text-bottom)也可以利用负margin - 自适应两列布局
<div>
<div style="height:100px;background-color:red;width:100%;margin-right:-200px;float:left">
我是红色块,我是自适应的
</div>
<div style="height:100px;background-color:blue;float:left;width:200px">
我是蓝色块,固定宽度200px
</div>
</div>
- 垂直居中
万能的垂直居中:position+负margin
<div style="height:100px;width:100px;background-color:red;position: relative">
我是红色块
<div style="background-color:blue;position: absolute;top:50%;left:50%;margin-top:-25px;margin-left:-25px;width:50px;height:50px">
我是蓝色块,在红色区域垂直居中
</div>
</div>
网友评论