Using overflow:auto to Clear Floated Content in CSS

For a long time, I used something like <div style="clear:both"></div> or its class equivalent to clear floated content in layouts. I knew, at some level, there were better solutions, but as these things go– I had deadlines to meet, had a working solution and there was never any inducement to look for a new one. Sure, there was a little extra markup, but it was so limited I could live with it.

Then in a comment on another post here ArkRep gift wrapped a better solution- one I vaguely knew about but had never explored. It looked a little something like this:

.clr {
clear:both;
}
.clr:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
.clr {display: inline-block;}

Liking it, since it swapped the useless markup hack thingie for a single class, I took a modified version of his code and moved it into our baseline screen.css at work. I then passed along the addition to the rest of the team. One of them (hi Ryan*), started to do some research into the code above and as an adjunct of that research came across a solution to the problem that was so simple and so clean that it really annoyed me that I didn’t know about it until last week. You can read about the solution in depth at the Sitepoint Blogs (3 years old!)

The simple and clean solution? Use overflow:auto on the containing div and it will, er, contain. Look at this simplified version:

Here’s the relevant CSS:

#container #content {
	overflow:auto;
	border:1px solid gray;
}
#container #copy {
	width:140px;
	border:.1em solid #CFCFCF;
	float:left;
	border:1px solid green;
}
#container #sidebar {
        width:140px;
	overflow:auto;
	float:right;
	blorder:1px solid pink;
}
#container #content #sidebar #sidebar-0{
	float:left;
	border:1px solid orange;
	}
#container #content #sidebar #sidebar-1{
	float:right;
	border:1px solid purple;
	}
#container #content #sidebar #sidebar-0,
#container #content #sidebar #sidebar-1 {
	width: 65px;
}
#container #footer {
	border:1px solid black;
}

I wish there was more to write about, but it’s really that simple. The biggest concern is that your math must work or else you’ll get scrollbars. With other versions of clearing floats, you were allowed to be a little looser with the calculations- if your sidebar actually leaked (overflowed) into the gutter beyond the edge of your container it didn’t actually matter since it would display correctly. With overflow:auto you don’t have that luxury. Of course, who wants to be sloppy? 🙂

*link? Where should I link?

4 thoughts on “Using overflow:auto to Clear Floated Content in CSS

  1. Ah ….. an even simpler solution than mine… nice research Rob.. I’ll be adding that to my CSS styles form now on..

    Ark

  2. Thanks, really useful! Was trying to fix my overflow problem with my content/sidebar and I found this 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *