You can use the new display: flow-root value today. It’s available in Firefox 53 and Chrome 58 which both have been released this week. And thanks to @supports, we can easily apply it already.

Visit Demo on JSBin directly.

Native “clearfix”

Rachel Andrew has a good introductory article on the new native method to fix containers with floats inside. The new display value has only recently been specified and is now available in major browsers already. The overall browser support is not yet extremely broad but thanks to other technologies available, we can use still use it.

Old “clearfix”

The old clearfix is something we’ve been using for years already in the web, if not decades. The latest iteration of it can be found here and is already quite slim. However, it remains a hack.

Using display: flow-root today

Here’s how you can use the new property today. Let’s start with basic HTML markup:

<div class="wrapper">
    <div class="left">Yo, this is a long text here that’s floated to the left, and while that’s cool it was always an issue in CSS since the parent needed a fix to adjust its height to the floated element.</div>
    <div class="right">Yo, this is a shorter text here that’s floated to the right.</div>
</div>

Our CSS now looks like this:

.left,
.right {
    width: 50%;
}

.left {
    float: left;
    margin-bottom: 2em;
}

.right {
    float: right;
}

.wrapper::after {
    content: '';
    display: block;
    clear: both;
}

@supports (display: flow-root) {
    .wrapper {
        display: flow-root;
    }

    .wrapper::after {
        content: none;  
    }
}

You can see that we apply the traditional clearfix to the wrapper class and if display: flow-root is supported, we unset it and instead use the more modern approach to ensure the wrapper element spans around the floated elements entirely.

As mentioned earlier, there are possible alternatives if you have to support different browsers. For example, if you don’t need to support IE11, you can also set the traditional clearfix only when the support for flow-root has been negated:

.wrapper {
    display: flow-root;
}

@supports not (display: flow-root) {
    .wrapper::after {
        content: '';
        display: block;
        clear: both;
    }
}

Here is the link to the Demo on JSBin again.


Note that Opera Mini doesn’t fully support @supports which is why my example would be broken there. Theoretically, you could apply the old clearfix code and the new flow-root property both but then I’d say the latter is not necessary and is only duplicate code.


Anselm is founder of Colloq, freelance frontend developer and publishes an industry-leading web development newsletter.

Like it?
Hire me!