开发者

floated inner <div> flows out of surrounding <div>

Please help me to understand why the image-div of the following code flows out of the box-div.

<body>
    <div id="box" style="border: 2px solid green;">
            <div id="image" style="height: 200px; width: 200px; background: red; float: left;"></div>
            <div id="text" style="background: yellow;">This is some text</div>
    </div>
</body>
开发者_C百科

In other words, I expected the green border to fully enclose both inner divs and not only the yellow one.


When a children its floating the parent doesn't wrap it. You can use two solutions for this:

#box{
     overflow:hidden;
}

Or

#box{
     float:left;
}

You can also use display:inline-block for the #box but that doesn't work on IE6


setting overflow to hidden is not always an ideal solution, as if you do have content which is larger than the container, it will not be displayed.

by adding a clearing element at the bottom of the container, you should see that the floated elements fit inside the parent.

<body>
    <div id="box" style="border: 2px solid green;">
            <div id="image" style="height: 200px; width: 200px; background: red; float: left;"></div>
            <div id="text" style="background: yellow;">This is some text</div>

            <div style="clear: left; height: 0; margin: 0; padding: 0"></div>
    </div>
</body>

Obviously, you'll want to make a generic class for this and set the CSS in an external stylesheet - but the principle works.


Floated elements are allowed to extend beyond their parent element. To keep the floated element inside the containing element, you will need to add an empty element at the end that clears the float:

So inside the element with id="box", add something like this:

<div style="clear: left;"></div>


You have to use an element to "clear" the floated object, using style="clear: left;"

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜