Floated Child Elements: overflow:hidden or clear:b

2019-01-13 13:37发布

问题:

As a web developer I frequently will have two floated (child) divs inside of another (parent) div. Actually I do this all day long.

<style type="text/css">
    #left {float:left;}
    #right {float:right;}
</style>
<div id="parent">
    <div id="left" class="child">&nbsp;</div>
    <div id="right" class="child">&nbsp;</div>
</div>

This doesn't work without an extra bit of css/html because the parent doesn't automatically grow to fit floated children. There are two popular ways of overcoming that:
1) Add overflow:hidden to the parent's css.
2) Add a 3rd "clearing" child <br style="clear:both;" />.

I know there's a few other similar questions about such things, but my question is:

Which method is better and why? What are the pros and cons of each?

回答1:

  1. Hidden overflow - pretty solid method. The main disadvantage is if you set a height on the parent element, any overflow will be...well, hidden. I found this when creating a menu with floated list items - the submenus would not appear.

  2. Clearing element - rather than a line break, I would use a div with height: 0; clear: both; since it won't create a gap below. This is a more solid method, the only disadvantage being an extra element in the markup.

  3. Float the parent - in my experience there are too many situations where you don't want to float the parent element, so I would avoid it.

  4. You can also use the generated content method:

    #parent:after {
      content: ".";
      visibility: hidden;
      clear: both;
    }
    

    This saves the need for an extra element in the markup, but it won't work in IE7 and below.

  5. Use inline blocks - just remembered this method. Instead of floating the two columns, set them to display: inline-block and they will appear side-by-side:

    .child {
      display: inline-block;
      vertical-align: top;
    }
    

    Only thing you must remember with this method is if there is any whitespace between the close tag of one block and the opening tag of another, a space will appear between the columns (the size of which depends on the font so it difficult to gauge). As long as you do ...</div><div id=... then this method works fine and is superior to floating elements IMO.



回答2:

The second is totally unnecessary and adds extra markup. Just something else to go wrong. Use the first if it fits the bill. You can also float the parent element to do the same thing though it might not fit what you're doing.



回答3:

PPK discusses this in Clearing floats over on QuirksMode.