Code Snippets
/

Classic Clearfix Techniques

Classic Clearfix Techniques

Clearfix solves the classic float-collapse problem: a parent that contains only floated children has zero height. Modern flexbox and grid layouts make floats almost obsolete, but every codebase still has legacy CSS where you have to fix this. This snippet shows the modern `display: flow-root` one-liner alongside the historical pseudo-element clearfix and the empty-div trick, so you know what you are reading when you open old stylesheets.

CSS
Easy
2 snippets
css-positioning
css-pseudo-elements
css-display

275 views

3

/* MODERN: one declaration, no markup change. display: flow-root creates a new
   block formatting context, which contains floats automatically. Use this on
   any parent that has floated children. Supported in every browser since 2018. */
.container {
    display: flow-root;
}

/* CLASSIC pseudo-element clearfix. Still seen everywhere; works back to IE 8.
   Adds an invisible block element after the parent's content that clears
   floats above it, forcing the parent to grow to contain them. */
.clearfix::after {
    content: "";
    display: block;
    clear: both;
}

/* Example: a card with two floated columns. */
.card {
    border: 1px solid #ddd;
    padding: 1rem;
}

.card .col-left {
    float: left;
    width: 60%;
}

.card .col-right {
    float: right;
    width: 35%;
}

/* Apply EITHER .clearfix on the parent OR display: flow-root.
   Do not use both; flow-root makes the pseudo-element redundant. */
.card {
    display: flow-root; /* preferred */
}

Use display: flow-root for any new code. It creates a new block formatting context, which has the side effect of containing floats inside the element, and it does so in a single declaration with no extra markup. The pseudo-element .clearfix::after { content: ""; display: block; clear: both; } is the version you will recognize from countless legacy codebases, including Bootstrap 3 and earlier. Both achieve the same result; the pseudo-element variant only exists because flow-root was not interoperable until 2018. Pick one technique per project and stick to it; mixing both on the same element is harmless but redundant.