Clearing Floats | August 19, 2003

As most of you probably know, when you float an element it no longer takes up any space in the document flow, causing borders and background colours to behave strangely.

To get round this you need to add some content to the container element and set that content to have a clear: both; style. Most people do this by using either

<br class="clear" />


<div class="clear"> </div>

However I found a number of problems with both these methods. Firstly they both add extra vertical space. Often this is OK, but in precisely controlled layouts this is a problem. Using the <br /> also produced problems and I was told on the css-discuss list that you really need to use a block level element like a div to get it to work in all browsers.

While on my usual internet trawls I came across a site where the owner had tested a wide variety of methods designed not to produce extra whitespace. I'd love to give this guy a credit but I can't for the life of me track down the site. If I do i'll post up the details.

Basically instead of using a no breaking space inside a div, it was suggested that an empty comment tag was used instead.

<div class="clear"><!-- --></div>

And that the styles contained a height declaration as well.

.class {
  clear: both;
  heignt: 0;

This may not be news to some, but It's something I've never come across before and seems extremely useful. I know some people will see it as a bit of a hack and it could spark off the whole design vs semantic mark-up debate again. However there are times when you really need to use hacks and this one seem to be doing a good job so far.

Posted at August 19, 2003 9:29 PM


jake said on August 20, 2003 3:04 PM

Interesting… I’ve been using similar (+ font-size: 1px;) css for a while. But I have a non-breaking space instead of an empty comment. I’ll have to remember that in the future. Thanks.

Gus said on August 20, 2003 10:31 PM

I don’t have a problem with hacks per se. In fact I think some are not only useful but beautiful as well. However…
The XML specs allows servers to strip regular comments out of an XML file before sending the data.
I don’t think servers actually do this yet, but this type of server behaviour could cause the empty comment hack to stop working in an XHTML document. In theory. Sometime in the future. Perhaps.

Rick Yribe said on December 20, 2003 4:25 AM

Not sure if you are aware, or if you meant it, but in your sample CSS you have .class while in the html preceding it you have class=”clear”. Just a heads up, if that’s not what you intended.