CSS Tutorial

Nov 30

How to clear floats so they expand around their content


This tutorial will show you how to fix the common problem of elements not expanding around their content. If you use floats, and you notice the container element does not increase in height as the content does, this is the solution for you.


I have been doing some styling changes on TipClique, and I noticed a problem after one of the changes I applied. The problem was an HTML element that contained floating elements did not expand around the content. I have used many methods in the past for correcting similar problems i.e. floating the container element, but I wanted to find a more sensible solution. After searching for a solution, I came across the following section on W3C.

In addition, if the element has any floating descendants whose bottom margin edge is below the bottom, then the height is increased to include those edges. Only floats that are children of the element itself or of descendants in the normal flow are taken into account, e.g., floats inside absolutely positioned descendants or other floats are not.

After searching a bit more, I found a solution that made sense. If you add overflow:auto to the container element its height will increase accordingly. Below is a code example of a container and child class that use this method.
#content{
	overflow:auto;
	border:1px solid red;
}
#sidebar {
	float:right;
	background-color:silver;
	height:150px;
	width:300px;
}
Here is the HTML for this example.
<div id="content">
    <div id="sidebar">
        Sidebar
    </div>
    Content
</div>
This all works perfectly in Firefox, but since so many people are stuck on IE a fix for that needs to be added. I don't use any CSS hacks anymore since the IE conditional statements eliminate the need for them, but either way the container element would need height:1%; added in a conditional section for the non-hack method, or _height:1%; for the hack method.




Clique It

Posted by , in CSS Tutorials



Leave a Comment

You must login or register to post a comment.



2 Members in Clique