显示:块; VS显示:table;

display: block; VS display: table;

我看不出 display: block;display: table; 之间的区别。例如,在编写 clearfix 时,以下两个 CSS 规则似乎行为相同:

Using display: block;

.clearfix:after {
  content: "";
  display: block;
  clear: both;
}
<div class="clearfix">
  <div style="float: right">Sidebar</div>
</div>
<p>
  Content
</p>

Using display: table;

.clearfix:after {
  content: "";
  display: table;
  clear: both;
}
<div class="clearfix">
  <div style="float: right">Sidebar</div>
</div>
<p>
  Content
</p>

所以我的问题是:display: block;display: table; 有什么区别?

如果你不使用 clearfix hack,区别就更明显了!

<p>With display:table you get</p>

<div style="display:table; border:1px solid">
  This is a table
</div>

<p>And with display:block you get</p>

<div style="display:block; border:1px solid">
  This is a block
</div>

所以为了一点点食物,你可能会问 display:tabledisplay:inline-block 之间有什么区别......

正如您从下面的演示中看到的那样,应用于 .clearfix::afterdisplay: table; 可防止 clearfix 的最后一个子项的底部边距与 [=14] 的底部边距重叠=] 本身,而 display: table; 仍然允许折叠。

.clearfix_table,
.clearfix_block {
  background-color: silver;
}
.clearfix_table::after,
.clearfix_block::after {
  content: "";
  clear: both;
}
.clearfix_table::after {
  display: table;
}
.clearfix_block::after {
  display: block;
}
<div class="clearfix_table">
  <p>text</p>
</div>

<hr>

<div class="clearfix_block">
  <p>text</p>
</div>