2

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?

Cameron Martin
  • 5,952
  • 2
  • 40
  • 53

1 Answers1

2

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/

Jonathan Nicol
  • 3,158
  • 1
  • 21
  • 22
  • This works really well, thanks. haslayout can be triggered by `zoom:1;`. – Cameron Martin Jun 14 '12 at 02:24
  • I like to avoid using zoom:1 if I can, just because it seems like a redundant declaration. But if you do wind up using this method, test in IE and I reckon most times it will work without any tweaks/hacks required. I have a feeling it might have been IE6 that used to cause me issues sometimes, because it's ages since I noticed any float clearing problems in IE. – Jonathan Nicol Jun 14 '12 at 02:30
  • Its not redundant if it's needed to trigger hasLayout. If its just IE6 that has these problems I won't bother supporting it since its a very outdated browser. – Cameron Martin Jun 14 '12 at 02:38
  • The downside of this approach is if the parent has text that is wrapping around the outer floats, then it will cause the parent width to shrink to fit next to the external floated blocks and the parent text content will no longer wrap around the external floats. – Richard S. Hall Nov 12 '13 at 15:16