CSS Layout: Part III
Nesting Floats
Looking over the last example in Part II, we can add a few new bits of CSS to allow for rendering nested floats correctly. In some recent projects, I have found a need to clear floats inside one of page’s two main columns. Unfortunately, because these main columns are also being floated, some browsers will render the layout in the way you would want it. An example has been created to better show the problem. For this example, we have switched the content to the right and the sidebar to the left. Because of this switch, the CSS has been modified. Also, we have added three floating images with captions inside the content block. A block of text should follow directly below the three images. When viewed in certain browsers mentioned below, you will see that this block of text falls a great distance below the images. It actually falls inline with the ending of the sidebar block. Let’s look at the example to clarify what I have just attempted to explain.
This example only renders to how we intended in Mozilla-type browsers (Netscape 6+, Firebird, Firefox, and Mozilla). But how do we fix for all the rest? Well, before we can discuss a fix, we should get to know the code involved in making this example. The following code has been added to the code from the last example in Part II.
<div id="content">
Content in here.
<div class="image">
<img src="image.jpg" alt="image" />
<p>Image</p>
</div>
<div class="image">
<img src="image.jpg" alt="image" />
<p>Image</p>
</div>
<div class="clear"></div>
Content that follows the images.
</div>
div.image {
margin: 0;
padding: 0 15px 0 0;
float: left;
width: 100px;
}
div.clear {
clear: both;
}
Now we can start the fixing! The key to tackling the rendering problem in this technique is to actually float both of the two main columns. Of course, to work consistently over browsers, both columns must be given widths.
#sidebar {
margin: 0; padding: 20px;
float: left;
width: 210px;
}
#content {
margin: 0; padding: 20px;
float: left;
width: 460px;
}
There was a catch to floating the three images. I especially noticed that IE5/Mac would
not float the images correctly without giving the divs wrapped around each
image a width.
And there you have it.
It took awhile to find a solution, but I finally found someone that must have had the same problem. This site also includes some other great CSS tests/techniques.
