Best Way To Clear Floats

Float bug screenshot

One of the greatest challenges of a CSS developer would be dealing with floated elements that “spill” its contents outside the parent element. This is known as the float bug. Fortunately there are many techniques to address this issue. One method involves creating an additional blank element, which I find semantically wrong but it does get the problem fixed.

A “semantically correct” fix should only involve elements that already exist. The quirksmode.org technique is probably the best way to achieve this.

The code looks like this:

div.container {
	border: 1px solid #000000;
	overflow: hidden;
	width: 100%;
}

div.left {
	width: 45%;
	float: left;
}

div.right {
	width: 45%;
	float: right;
}

It is a purely CSS solution that does not require any additional tags. All you need to do is add a width and overflow rule to the parent element. The technique works flawlessly on all the major browsers: Internet Explorer 6+, Firefox 2+, Safari, and Opera.

Happy coding!

5 Responses to “Best Way To Clear Floats”

  1. Jay Says:

    Nothing is flawless. Causes problems when clicking to the left of the container in FireFox. Not sure about the latest version as I have given up on this method.

  2. Ivan Nikolic Says:

    Also, if you try to use positioning with negative top value (not sure about bottom value) on the box contained in the parent element with overflow: hidden value, it cuts of the box that is being positioned. I found that best solution for this is also float the parent element.

  3. Welcome to Paradise Says:

    It coding was quite useful to me. But still I had to make a little bit of adjustments here and there. I think you need to put in a second version of this code.

  4. H5N1 Says:

    Try the “overflow : auto” settings to blow these issues off.
    It requires only some height value adjustment.

  5. Optimization css Says:

    Overflow: Auto, should be required to designate a high!

Leave a Reply