Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clearing floats for just parent container, not ancestors?

Tags:

css

css-float

I have the following layout with 2 level float containers:

<div id="navigation" style="float: left; width: 150px; height: 200px; background-color: #eee">Navigation</div>
<div id="container" style="margin-left: 150px; background-color: #f00">
    <div style="float: left; width: 50%; height: 100px; background-color: #ff0">Block</div>
    <div style="float: left; width: 50%; height: 20px; background-color: #f0f">Block</div>
    <div style="clear: both"></div>
    <div style="float: left; width: 50%; height: 50px; background-color: #00f">This Block</div>
</div>

You can see it live at http://jsfiddle.net/dNmNj/ .

My intention is to clear floats for #container so that the blue block (This Block) stays right below the yellow one (not the pink one). However, the result is that it also cleared floats for #navigation.

How do I clear floats just for the parent container and not any ancestor containers?

like image 417
He Shiming Avatar asked May 10 '13 13:05

He Shiming


1 Answers

You can achieve what you want by adding overflow:hidden to your #container:

http://jsfiddle.net/dNmNj/2

this is a good article about clearing floats

http://www.quirksmode.org/css/clearing.html

but the reason your blue div is dropping where it is is because the #container div is not floated - just margin left

The following shows a reworking which is more cross-browser compatible:

http://jsfiddle.net/dNmNj/3/

like image 112
Pete Avatar answered Sep 20 '22 14:09

Pete