Question

The most popular way of clearing a group of floats is to use clear:both; on the parent's :after pseudo-element. For example this:

.group:after {
    visibility: hidden;
    display: block;
    content: "";
    clear: both;
    height: 0;
    }
* html .group             { zoom: 1; } /* IE6 */
*:first-child+html .group { zoom: 1; } /* IE7 */

This works fine in most cases, but it fails when you have floated elements within floated elements. It clears all floats, not just the child floats.

A possible way of fixing that is by adding

.group {
    display:inline-block;
}

But this can have unwanted side-effects.

Is there any way of clearing only child floats, instead of every float on a page?

Was it helpful?

Solution

My preferred method for clearing floats is actually to set the containing element's overflow property to auto:

.group {
    overflow: auto;
}

overflow: hidden will work too.

This will force .group to clear any floated children, but it won't clear any other floats on the page. I think this is probably what you want to achieve?

Sometimes this method won't force old versions of IE to clear floats (sorry, I can't recall which version of IE exactly), in which case you need to force haslayout for IE. Setting an explicit width on .group would do it. But for the most part I find this method "just works".

Here's a demo: http://jsfiddle.net/C7KWn/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top