揭开clearfix和overflow的神秘面纱 🔑 clearfix Reloaded + overflow:hidden Demystified

About the author: Thierry Koblentz is a front-end engineer at Yahoo!
He owns TJK Design and ez-css.org. You can follow Thierry on Twitter at @thierrykoblentz
.

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:

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:

Further reading

 

 

from:  https://yuiblog.com/blog/2010/09/27/clearfix-reloaded-overflowhidden-demystified/

Relate: How to make absolute positioned elements overlap their overflow hidden parent

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注