Last Updated: February 25, 2016
·
436
· ozzysong

Clearing floats without markup

The usual way of clearing css floats without markup was applying overflow:hidden to the element containing the floated elements.

The problem with this is because overflow of the element is hidden, negative margin or absolute position set part of the element invisible.

Happily for us, web developers, there's an elegant way of clearing floats without markup using pseudo elements:

HTML

<div class="container">
    <div style="float: left;">floating left!</div>
    <div style="float: right;">floating right!</div>
</div>

CSS

.container:after{
     content: '.'; height:0;
    display: block; visibility: hidden;
    clear: both;
}

What this does is creating an invisible element before all .container contents allowing to clear both floats without any markup.

A word of warning on Internet Explorer (of course!): Full support for :after pseudo element started on IE8 but there are some hacks to make it fully working on previous versions.