Say Goodbye to the Clearfix Hack With display: flow-root

The clearfix hack has been around for a long time now, and patches a problem that can happen with floating elements that are larger than their container.

Here’s an example of the problem:

.box {
  padding: 1rem;
  background: rgba(255, 213, 70, 0.1);
  border-bottom: 2px solid rgba(236, 198, 48, 0.2);
}
.box img {
  float: left;
}
<div class="box">
  <img src="/images/pirate.svg" width="150" alt="Pirate!">
  Alice was beginning to get very tired of sitting by her sister on the
bank...
</div>
Pirate! Alice was beginning to get very tired of sitting by her sister on the bank...

Clearfix

The fix is to set overflow: auto on the container, so a class like this is often created and used on elements that contain floated elements:

.clearfix {
  overflow: auto;
}
<div class="box clearfix">
  <img src="/images/police.svg" width="150" alt="Police!">
  Alice was beginning to get very tired of sitting by her sister on the
bank...
</div>

And now everything works as expected:

Police! Alice was beginning to get very tired of sitting by her sister on the bank...

display: flow-root

With display: flow-root on the container element, a new block formatting context is established for the element with flow layout formatting, and this fixes our overflowing issues without resolving to what is essentially a hack:

.box {
  display: flow-root;
  padding: 1rem;
  background: rgba(255, 213, 70, 0.1);
  border-bottom: 2px solid rgba(236, 198, 48, 0.2);
}
<div class="box">
  <img src="/images/chef.svg" width="150" alt="Chef!">
  Alice was beginning to get very tired of sitting by her sister on the
bank...
</div>
Chef! Alice was beginning to get very tired of sitting by her sister on the bank...

Browser Support

Can I Use flow-root? Data on support for the flow-root feature across the major browsers from caniuse.com.

✖ Clear

πŸ•΅ Search Results

πŸ”Ž Searching...