技巧杂烩

margin-top 溢出解决

前端CSS

margin-top 溢出解决

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

<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添加内容

示例:

.f:before {
    content: '';
    display: table;
}
.f:before {
    content: '.';
    display: block;
    height: 0;
    visibility:hidden;
}
.f {
    border-top: 1px solid transparent;
}

文章标题:margin-top 溢出解决

文章作者:浅小沫

文章链接:https://blog.truimo.com/posts/margin-top-overflow


您可以自由在任何媒介以任何形式分享本作品,但需署名,且不得用于商业目的或改编。若分发衍生作品,须采用相同的许可协议。

本博客的所有原创内容采用 CC BY-NC-ND 4.0 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议 进行许可。