clearfix and overflow
:hidden
may be the two most popular techniques to clear floats without structural markup.
This short article is about enhancing the first method and shedding some light on the real meaning of the second.
clearfix
In everything you know about clearfix is wrong I explain the issues this method creates across browsers and I suggest to only use clearfix on elements that are not next to floats (e.g. a modal window), although as authors we still have to deal with collapsing margins. This demo page demonstrates the issue.
Margin-collapse behavior in the first two boxes shows that it is the generated (non-empty) content that keeps the bottom margin inside the box (which makes perfect sense according to spec).
So, to create the same box layout across browsers we can enhance the original method by generating content using both pseudo-elements :before
and :after
:
1 2 3 4 5 6 7 8 9 | .clearfix:before, .clearfix:after { content: "."; display: block; height: 0; overflow: hidden; } .clearfix:after {clear: both;} .clearfix {zoom: 1;} /* IE < 8 */ |
Don’t simply replace your clearfix rules with these new ones in existing projects, though, as you may have already patched issues related to collapsing margins via other methods.
overflow
In most discussions about clearing floats the overflow:hidden
method comes up, and it is always shot down by a “If you’re placing absolutely positioned elements inside the div, you’ll be cutting off these elements“. But this is not necessary true. overflow:hidden
will always clip relatively positioned elements, but it will not always hide absolutely positioned ones. This is because it all depends on the containing block:
10.1 Definition of “containing block”:
4. If the element has ‘position: absolute’, the containing block is established by the nearest ancestor with a ‘position’ of ‘absolute’, ‘relative’ or ‘fixed’, …
This means absolutely positioned elements will show outside of a box styled with overflow:hidden
unless their containing block is the box itself or an element inside the said box.
You can check this demo page to see how things work.
Better alternatives
If you can apply a width to the element containing floats, then your best option is to use:
1 2 | display: inline-block; width: <any explicit value>; |
Further reading
- Contained Floats, enclosing floats with pure CSS known as the clearfix technique
- How To Clear Floats Without Structural Markup
- The New Clearfix Method
- 10.1 Definition of “containing block”
from: https://yuiblog.com/blog/2010/09/27/clearfix-reloaded-overflowhidden-demystified/
Relate: How to make absolute positioned elements overlap their overflow hidden parent