Explain Codes LogoExplain Codes Logo

Using :after to clear floating elements

html
responsive-design
css
clearfix
Nikita BarsukovbyNikita Barsukov·Nov 9, 2024
TLDR

Greatly simplifying layout management, utilize the clearfix hack with ::after to make sure that a container neatly encapsulates its floated children:

.clearfix::after { content: ""; display: table; clear: both; }

Then, comfortably add .clearfix to the said container:

<div class="clearfix"> <div style="float: left;">Item 1</div> <div style="float: left;">Item 2</div> </div>

Voilà! The container self-clears its floats, upholding the layout integrity with zero extra markup.

Clearfix hack: Comprehensive guide

The clearfix hack is an accepted solution for handling the peculiarities of floated layouts. While simple, this approach allows flexibility and variations to take care of older and less compatible browsers.

Clearfix: Enhanced version for universal applicability

For legacy browsers such as IE6 & IE7, we add a little extra spice to our clearfix to ensure smooth sailing:

.clearfix::before, .clearfix::after { content: "."; visibility: hidden; display: block; clear: both; /* Say goodbye to float 🎈🎈🎈 */ height: 0; } .clearfix { /* because block would be too mainstream */ display: inline-block; } /* Because 🦖 IE 6/7 still roam the Earth */ .clearfix { zoom: 1; }

Live demo: Clearfix in action

A picture is worth a thousand words. But, when it comes to code, a live sample is priceless. Grasp the clearfix method in an interactive manner with this jsfiddle example:

  • [Example]: This URL would link to a jsfiddle.net example demonstrating clearfix in action.