Search code examples
htmlcsslayoutcss-floatclearfix

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


Solution

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