开发者

why div background does not contain inner element unless floated?

开发者 https://www.devze.com 2023-03-23 17:09 出处:网络
I have a block of html like this. Judging by the background color of the divs, the outer div is not containing the inner div, unless I remove \"float:left\" from the inner div, or add \"float:left\" t

I have a block of html like this. Judging by the background color of the divs, the outer div is not containing the inner div, unless I remove "float:left" from the inner div, or add "float:left" to the outer div. Why is that? http://jsbin.com/ihiqoz/2/edit

<div style="width:900px; background-color:#1EFF1E">
    <p>outside</p>
    <div style="float:left; width: 25%; background-color:#BD78C8">
        <p>inside</p>
    <开发者_如何学C/div>
</div>


You need to clear your float:

<div style="width:900px; background-color:#1EFF1E">
    <p>outside</p>
    <div style="float:left; width: 25%; background-color:#BD78C8">
        <p>inside</p>
    </div>
    <div style="clear: left;"></div>
</div>

Floating elements break out of the layout, so your div doesn't get considered by the elements around it. The clear css property forces an element to move after the last floating element, so when you place an empty div below your floating element by giving it the clear style, the outer div will stretch to contain it.


@ray; if you have float in your child element so you have to clear it's parent so just write overflow:hidden in it's parent div to clear it.

For Example:

<div style="width:900px; background-color:#1EFF1E; overflow:hidden">
    <p>outside</p>
    <div style="float:left; width: 25%; background-color:#BD78C8">
        <p>inside</p>
    </div>
</div>

read this article for more http://www.quirksmode.org/css/clearing.html


You can also add <BR> at the end of the div, after the floated one.

Edit: You need to clear the div.

0

精彩评论

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