Nested floats require some basic knowledge of how CSS floats actually work. The first thing you need to know is that a floated element automatically contains another floated element (from the point of view of containing floats). Another important thing to note is that floated elements automatically push other elements to another line when there's no more room available on the line where they are enclosed. Let's say that we have an HTML structure like this:
<div id="container"> <div id="left"> <div id="left-1"></div> <div id="left-2"></div> <div id="clear-1"></div> </div> <div id="right"> <div id="right-1"></div> <div id="right-2"></div> <div id="clear-2"></div> </div> <div id="clear"></div> </div>
So we have a container, two sub-container and three other elements within such containers. We can write the following CSS code:
#container { width: 450px; background: gray; overflow: auto; } #left { float: left; width: 200px; height: 200px; background: orange; } #right { float: right; width: 200px; height: 200px; background: crimson; } #left-1 { float: left; width: 90px; height: 100px; background: teal; } #left-2 { float: right; width: 90px; height: 100px; background: fuchsia; } #right-1 { float: left; width: 90px; height: 100px; background: silver; } #right-2 { float: right; width: 90px; height: 100px; background: maroon; } #clear-1, #clear-2, #clear { width: 90%; margin: 0 auto; height: 50px; background: yellow; clear: both; }
First we take care of containing floats by specifying overflow: auto
on the main container. This works because this declaration actually prevents vertical space from collapsing. Then we float every box inside the two sub-containers and the other elements within these boxes with the exception of the three elements that need to be cleared. You can see the result of this test below.
As you can see, in our test we only needed to add the declaration clear: both
to the yellow boxes. This is due to the fact that all floats inside the main container are not wide enough to fill the line that encloses them. If this was the case, then all yellow boxes would be automatically pushed on the next line, though no clearance would be added to them.
Very helpful description and example! Wish I had seen this two weeks ago when I needed to create exactly this float situation.
Thanks. More examples here www.css-zibaldone.com/test. :-)