Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
251 views
Welcome To Ask or Share your Answers For Others

1 Answer

  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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...