一、margin
margin是盒模型的外边框,但是在开发的过程中,会有一些特殊的现象,通过以下例子展示
合并
代码结构
#style
.wrap {
width: 200px;
height: 200px;
background-color: #000;
}
.top {
height: 50px;
width: 50px;
background-color:red;
margin-bottom: 50px;
}
.bottom {
height: 50px;
width: 50px;
background-color: blue;
margin-bottom: 25px;
}
#dom
<div class="wrap">
<div class="top"></div>
<div class="bottom"></div>
</div>
这里看到top和bottom的间距值的和是75px,但是通过查看dom节点,可以看到top和bottom合并了
这里能看到top和bottom如果有margin属性重叠,那么就以值最大的值50为准
margin塌陷
在这里给top设置属性
margin: 50px auto 20px;
能得到这样一个图
这会会思考,怎么会塌陷呢,不是好好的吗
接下来给wrap设置属性
margin: 50px auto;
得到这样的图
看下结构
发现top应该离上边距有50像素,但是实际上并没有,这里就是塌陷。 先不说原因,说下解决的方式,其实就是BFC(格式化上下文)
margin-bottom 负值
bottom 设置属性
margin-top: -10px;
我们能看到样式bottom的样式覆盖在了top上
但是设置top为负值时
margin-bottom: -10px;
我们会发现,上下节点,都是下节点覆盖到上节点上,
BFC的触发条件
- float除none以外的值
- position(absolute, fixed)
- display 为其中之一的值 inline-block,table-cell,table-caption
- overflow: hidden auto scroll
margin塌陷的原因
www.w3.org/TR/CSS2/box… 在这里看到了margin的规则
从相邻的垂直边距折叠规则下,这里是产生坍陷的原因