在写样式的时候,发现了一个问题:
<style>
.f {
background-color: #555;
}
.s {
margin-top: 10px;
background-color: #fff;
}
</style>
<div class="f">
<div class="s">内容</div>
<div class="s">内容</div>
<div class="s">内容</div>
<div class="s">内容</div>
</div>
我需要的效果:
实际效果:
这里.s
的margin-top
貌似跑到.f
去了,迷
经过Google搜索,找到以下文字:
CSS在盒模型中规定:
In this specification, the expression collapsing margins means that adjoining margins (no non-empty content, padding or border areas or clearance separate them) of two or more boxes (which may be next to one another or nested) combine to form a single margin.
所有毗邻的两个或更多盒元素的margin将会合并为一个margin共享之。毗邻的定义为:同级或者嵌套的盒元素,并且它们之间没有非空内容、Padding或Border分隔。
参考文档:Box model
触发条件:
- 父元素没有设置上边距
- 给第一个子元素添加上边距
解决方法:
- 给父元素添加上边距
- 给父元素设置上内边距取代子元素上外边距
- 给父元素设置上边框
- 使用
:before
添加内容
示例:
.f:before {
content: '';
display: table;
}
.f:before {
content: '.';
display: block;
height: 0;
visibility:hidden;
}
.f {
border-top: 1px solid transparent;
}
又一枚入坑折腾的小盆友@(懒得理)
欢迎入坑 @(真棒)