显示:块; VS显示:表格;

时间:2016-10-07 04:29:32

标签: html css layout css-float clearfix

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

  

使用display: block;

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

  

使用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;之间有什么区别?

2 个答案:

答案 0 :(得分:2)

正如您在下面的演示中所看到的,display: table;上应用的.clearfix::after会阻止clearfix的最后一个孩子的下边距与clearfix的下边距折叠本身,display: table;仍允许折叠。

&#13;
&#13;
.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;
}
&#13;
<div class="clearfix_table">
  <p>text</p>
</div>

<hr>

<div class="clearfix_block">
  <p>text</p>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

如果你不使用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之间的差异......