nalzok
nalzok

Reputation: 16117

display: block; VS display: table;

I can't spot the difference between display: block; and display: table;. For example, when writing clearfix, the following two CSS rule seems to behaviour identical:

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>

So my question is: What's the differences between display: block; and display: table;?

Upvotes: 3

Views: 2394

Answers (2)

nalzok
nalzok

Reputation: 16117

As you can see from the demo below, the display: table; applied on .clearfix::after prevents the bottom margin of last child of clearfix from collapsing with the bottom margin of clearfix itself, while display: table; still allows collapsing.

.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>

Upvotes: 3

Mr Lister
Mr Lister

Reputation: 46579

If you don't use the clearfix hack, the difference is much clearer!

<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>

So for a little food for though, you could have asked what the difference is between display:table and display:inline-block instead...

Upvotes: 1

Related Questions