技巧杂烩 · 

margin-top 溢出解决

在写样式的时候,发现了一个问题:

html

<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>

我需要的效果:

实际效果:

这里.smargin-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添加内容

示例:

css

.f:before {
    content: '';
    display: table;
}

css

.f:before {
    content: '.';
    display: block;
    height: 0;
    visibility:hidden;
}

css

.f {
    border-top: 1px solid transparent;
}

margin-top 溢出解决

creative commons