Clear floats with overflow: hidden

Lately, I’ve seen a trend of programmers adding on new elements to pages in order to add a class to them to clear all of the floated elements in a container. Why? Simply use overflow hidden on the parent, and like a miracle, bam! The container becomes aware of all of the children elements.

The old way:

1
2
3
4
5
6
7
<ul>
    <li><a href="/">Text</a></li>
    <li><a href="/">Text</a></li>
    <li><a href="/">Text</a></li>
    <li><a href="/">Text</a></li>
    <li class="clearfix"></li>
</ul>
1
2
3
4
5
6
li {
    float: left;
}
.clearfix {
    clear: both;
}

The old way is not as effective, since we have to add additional elements that do not show anything. Their only purpose is to fix a css style. Why not do it in css? This method also adds what seems like an additional line that makes it seem like you have bottom margin, or padding. Too much to maintain and fix. Additionally, I believe at the time of this writing, google looks for empty elements and dings you if you don’t put anything in them. Validate your HTML. Be a good programmer.

The new way:

1
2
3
4
5
6
<ul>
    <li><a href="/">Text</a></li>
    <li><a href="/">Text</a></li>
    <li><a href="/">Text</a></li>
    <li><a href="/">Text</a></li>
</ul>
1
2
3
4
5
6
ul {
    overflow: hidden;
}
li {
    float: left;
}