By Simon Willison

Clearing Floats

By Simon Willison

A frequent point of confusion with the CSS float model is the need for a “clearing” element beneath something that is floated if you want the containing element of the float to fully contain it. Eric Meyer’s Containing Floats provides an excellent explanation of this issue.

Unfortunately, the standard method for dealing with this involves adding ugly additional markup to the document to act as a “clearer”. It is often possible to take advantage of another element in the document, but frequently no such element is available and an extra clearing element must be added.

Tony Aslett has published an article (also discussed here) explaining a way around this problem. It starts with the observation that the CSS :after pseudo-element can be used in browsers with good CSS 2 support to add an effective clearing element using the CSS itself:


content: ".";
display: block;
height: 0;
overflow: hidden;
clear: both;

That’s enough to solve the problem in most modern standards compliant browsers, with the very notable (and not entirely unexpected) omission of Internet Explorer for both Mac and Windows. Tony proposes fixes for these browsers which take advantage of a number of CSS hacks, including one that relies on a documented bug in IE/Windows’s float model.

I tend to have a cautious attitude towards technique that involve multiple browser hacks, as there’s always the possibility of the undocumented bugs involved interacting in unpredictable ways. It’s worth reading upon the details of the technique as you will certainly learn something about the CSS float model and/or IE’s mistreatment of it but I would recommend caution when it comes to actually implementing it. Still, it’s another tool for the tool box.

The most important and interesting stories in tech. Straight to your inbox, daily. Get Versioning.
Login or Create Account to Comment
Login Create Account