为什么顶部边距正在崩溃但底部边距却没有?

Why top margins are collapsing but bottom margins are not?

在下面的demo中可以看到,在left-column中,.clearfix-using_display-table(黄色部分)的padding上边缘和.clearfix-using_display-table p(银色部分)的padding上边缘相互接触.但是,在下边缘,由于某种原因,两个边缘没有相互接触。

事实上,right-column 的布局是我认为 left-column 中的框应该看起来的样子。

.left-column,
.right-column {
  background-color: orange;
  width: 150px;
}
.left-column {
  float: left;
}
.right-column {
  float: right;
}
.clearfix-using_display-table,
.clearfix-using_display-block {
  background-color: yellow;
  width: 125px;
}
.clearfix-using_display-table p,
.clearfix-using_display-block p {
  background-color: silver;
  width: 100px;
  margin-top: 1em;
}
.clearfix-using_display-table:after,
.clearfix-using_display-block:after {
  content: " ";
  clear: both;
}
.clearfix-using_display-table:after {
  display: table;
}
.clearfix-using_display-block:after {
  display: block;
}
<div class="wrapper">
  <div class="left-column">
    <h3>Table</h3>
    <div class="clearfix-using_display-table">
      <p>Lorem Ipsum...</p>
      <p>Lorem Ipsum...</p>
    </div>
  </div>
  <div class="right-column">
    <h3>Block</h3>
    <div class="clearfix-using_display-block">
      <p>Lorem Ipsum...</p>
      <p>Lorem Ipsum...</p>
    </div>
  </div>
</div>

我猜这与保证金崩溃和新 BFC 的建立有关,但我不确定。有人可以帮我想想办法吗?

使用 "clearfix" 和 display: table 将保留底部边距,display: block 则不会。

来源:http://cssmojo.com/the-very-latest-clearfix-reloaded/

更新:为什么top margin崩溃是因为它的直接父级没有建立BFC


为了使页边距不折叠,添加一个 BFC,在本例中是在 p 父级上,如下例所示,通过添加例如 overflow: auto.

更多阅读:Mastering margin collapsing

更新:Why doesn't a <table>'s margin collapse with an adjacent <p>

.left-column,
.right-column {
  background-color: orange;
  width: 150px;
}
.left-column {
  float: left;
}
.right-column {
  float: right;
}
.clearfix-using_display-table,
.clearfix-using_display-block {
  background-color: yellow;
  width: 125px;
  overflow: auto;                      /*  establish BFC  */
}
.clearfix-using_display-table p,
.clearfix-using_display-block p {
  background-color: silver;
  width: 100px;
}
.clearfix-using_display-table:after,
.clearfix-using_display-block:after {
  content: " ";
  clear: both;
}
.clearfix-using_display-table:after {
  display: table;
}
.clearfix-using_display-block:after {
  display: block;
}
<div class="wrapper">
  <div class="left-column">
    <h3>Table</h3>
    <div class="clearfix-using_display-table">
      <p>Lorem Ipsum...</p>
      <p>Lorem Ipsum...</p>
    </div>
  </div>
  <div class="right-column">
    <h3>Block</h3>
    <div class="clearfix-using_display-block">
      <p>Lorem Ipsum...</p>
      <p>Lorem Ipsum...</p>
    </div>
  </div>
</div>