margin塌陷
父子嵌套元素在垂直方向的margin,子元素总是与父元素贴合在一起,他们两个的margin会取其中最大的值表现在父元素上
<div style="width:100px;height:100px;margin-top:100px;background:red;">
<div style="width:50px;height:50px;margin-top:50px;background:blue;"></div>
</div>

解决方法
- 触发BFC切断父元素与外部的联系
- 给父级设置边框/内边距
margin合并
兄弟元素在垂直方向上的margin并不会互相叠加,而是取较大值
<div style="width:100px;height:100px;margin-bottom:100px;background:red;"></div>
<div style="width:50px;height:50px;margin-top:50px;background:blue;"></div>

解决方法
- 为其中一个元素添加父元素并触发BFC,切断与另一个元素的联系
BFC
BFC(Block Formatting Context)格式化上下文,是Web页面中盒模型布局的CSS渲染模式,指一个独立的渲染区域或者说是一个隔离的独立容器。
满足以下任意条件的元素会形成一个新的BFC
- 浮动元素,float 除 none 以外的值;
- 定位元素,position(absolute,fixed);
- display 为以下其中之一的值 inline-block,table-cell,table-caption;
- overflow 除了 visible 以外的值(hidden,auto,scroll);
BFC特性
- BFC元素不会和其他元素间产生margin塌陷/合并
- BFC元素不会被浮动元素覆盖
<div class="column" style="float: left;width: 200px;height: 300px;
margin-right: 10px;background-color: red;"></div>
<div class="column" style="float: right;width: 200px;height: 300px;
margin-right: 10px; margin-left: 10px;background-color: red;"></div>
<div class="column" style="overflow: hidden;height: 300px;
background-color: purple;"></div>

- 清除内部浮动
网友评论