September 11th, 2008

Clearing Floats in a container, the easy way

Here's a common problem that perplexes some beginner CSS stylers, with an easy (but not obvious) solution.

When you float an element within a container, it seems to escape the bounds of the container and spill outside. What if you want the container to resize to contain the items floating within it?

I'll illustrate with examples. Note that I've used inline styles here because that makes it easier to cut-and-paste the examples, but the same principles apply when the styles are in an external CSS file.

Here is a simple container, with an image inside it.

This is how it renders:

Next, we float the image to the right.

See how the image spills out of its container? Floating the image does push the image over to the right, but now the container doesn't contain it. The solution is to put "overflow:hidden" on the parent.

Problem solved!

This technique still works fine when the text is longer than the image.

Quite simply, adding "overflow:hidden" tells the container that it should resize to fit the contents.

But there is a caveat. "Overflow" is usually used to handle items that are too large for their container element. Setting it to "hidden" means that anything in the container that exceeds the boundary will be cropped. To illustrate, I'll add a height to the container:

Now the container does "contain" the image, but it crops off the parts that overflow past its defined boundary. Sometimes this is what you want... but not in this situation.

So to summarize: if you have floated items within a container, and you want that container to resize to fit the floated contents, add "overflow:hidden" to the container, and do not define the size of that container.

Class adjourned!

Filed under Uncategorized

Leave a Reply