有没有办法完全禁用边距折叠?我发现的唯一解决方案(称为“不折叠”)需要使用1px边框或1px填充。我觉得这是不可接受的:多余的像素毫无理由地使计算复杂化。是否有更合理的方法来禁用边缘折叠?


当前回答

CSS* Fixes
display: flow-root;
✅ Parent element collapse
❌ Sibling element collapse
display: flex;
flex-direction: column;
✅ Parent element collapse
✅ Sibling element collapse

*现代浏览器(不包括IE11)支持display: flow-root和display: flex。

例子

section { background: green; outline: 2px solid purple; } p { background: yellow; margin: 1em 0; } section.flow-root { display: flow-root; } section.flex { display: flex; flex-direction: column; } <h2>Default</h2> <section> <p>Paragraph 1</p> <p>Paragraph 2</p> </section> <h2><code>flow-root</code> (Fixes only container)</h2> <section class="flow-root"> <p>Paragraph 1</p> <p>Paragraph 2</p> </section> <h2><code>flex</code> (Fixes both container & siblings)</h2> <section class="flex"> <p>Paragraph 1</p> <p>Paragraph 2</p> </section>

其他回答

事实上,有一个完美无缺的方法:

显示:flex; flex-direction:列;

只要你能接受IE10及以上版本

.container { 显示:flex; flex-direction:列; 背景:# ddd; 宽度:15他们; } .square { 保证金:15 px; 高度:3他们; 背景:黄色; } < div class = "容器" > < div class = "广场”> < / div > < div class = "广场”> < / div > < div class = "广场”> < / div > < / div > < div class = "容器" > < div class = "广场”> < / div > < div class = "广场”> < / div > < div class = "广场”> < / div > < / div >

每个基于webkit的浏览器都应该支持属性-webkit-margin-collapse。还有一些子属性仅用于设置顶部或底部边距。您可以为它设置值collapse(默认值)、discard(如果有相邻的边距,则将边距设置为0)和separate(防止边距崩溃)。

我已经在2014年版本的Chrome和Safari上进行了测试。不幸的是,我不认为这将在IE支持,因为它不是基于webkit。

阅读苹果的Safari CSS参考以获得完整的解释。

如果你查看Mozilla的CSS webkit扩展页面,他们将这些属性列为私有属性,并建议不要使用它们。这是因为它们可能不会很快进入标准CSS,只有基于webkit的浏览器支持它们。

供你参考 网格,但有副作用:)

.parent {
  display: grid
}

您还可以使用老式的micro clearfix。

#container::before, #container::after{
    content: ' ';
    display: table;
}

查看更新后的小提琴:http://jsfiddle.net/XB9wX/97/

Try

{
 display:flex;
 flex-direction:column;
}

or

{
   display:grid;
}