开发者

Why float behave differently than other options when we give float to parent element to clear float?

In this example http://jsbin.com/inoka4 no width is defined for parent element

if i want to wrap red boxes in container border.

then we can make this in 5 ways

  • to giving float also to <div class="container">
  • overflow:hidden or overflow:auto
  • any clearfix hack to <div class="container clearfix">
  • Giving height to <div class="container">
  • adding one more html element (for example another div or <br >) after 2 boxes in <div class="container"> enter code hereand give clear:leftor:bothor:right` to that element

my question is any other option except float do not make any changes in <div class="container"&g开发者_JAVA技巧t; and inner boxes width. but if we use float:left or right to parent box then it's shrink the whole box and inner-boxes as well.

Why?

example link: http://jsbin.com/inoka4

Edit: My question is not about which method i should use, the question is why Float shrink the width


I think the better option is to use overflow:hidden. It is a simple one line change and it works.

div#container {
    ...
    overflow: hidden;
}

Adding extra divs for clear fix requires changes in html for something that is really css. Alternatively, when using clear fix by doing hacks like...

div:after {
    content:....
    ...
}

your css just gets bigger and messier. But it still is a good option (especially when you need to have things that overflow the box)

Reference: http://net.tutsplus.com/tutorials/html-css-techniques/css-fudamentals-containing-children/


If you dont' use float on the container it's width is set to 100%. If you add a floating, it only takes the space it needs. In this case the width is calculated by the two divs inside.

To wrap the red boxes in the container border there is not other option except adding float to the container. The only other option would be to absolutely position all the elements but in this case you have to know the width and height of all elements in advance. So that really isn't an option.

So my advice is to use float on the container and add a clear: both on the element after the container.


Your best bet is to always clear your floats. Just after you close the div with class .right, and just before you close the div with class .container, add a new div like this:

<div class="clear"></div>

.clear is just {clear:both;} in your stylesheet. That's what I use all day long, and works like a treat.

The final markup would be:

<div class="container">
    <div class="left"> ... </div>
    <div class="right"> ... </div>
    <div class="clear"></div>
</div>

Edit: Just like your last example, apparently. :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜