OVERFLOW PROPERTY AND FLOATING ELEMENTS

One of the most common issues I’m asked about is how to keep elements that float to stay within the confines of their container. See the example below followed by the code:

.container {
background:#ccc;
border:3px solid red;
}

.container img {
float:left;
}

We basically have a div with a gray background color and a border. Within that div lie 2 child elements; a paragraph of text and an image floated to the left of the text. Now if there were more text, the border of the div would push down, essentially hiding our problem. What is happening is that the parent div is ignoring the height of the floated element (in this case, a Quake Live logo.) Now there are a few ways that we can address this:

The first would be to set a static height on the div. This can work well if you know how tall your content will be. Unfortunately, if this div contains dynamic content, we might not know how much content will be there at any given time.

The second option would be to add an additional div before the closing of the container div that has the clear:both attribute. This is a viable fix but when you get into multiple column layouts it can be problematic without the use of javascript. In addition, we want to use as few div‘s as possible in our layout as to keep the page light and organized.

So the answer to this question is actually pretty simple as you can see in the below code: (additions are in bold.)

.container {
background:#ccc;
border:3px solid red;overflow:auto;
}

.container img {
float:left;
}

Notice that the logo is now neatly tucked inside the container div. See below:

By simply using overflow (this property specifies what happens if content overflows an element’s box. -W3Schools.com), we are making the div aware of everything within it. We could use overflow:hidden or overflow:scroll but hiddenhas the potential of cutting off from view anything that might spill out of the div(though in this example it would work fine.) and overflow:scroll would add scroll bars around our div like an iframe and that is not our desire in this case.

Now there is just one thing we need to do to make this work in older versions of IE and Opera. That is to give the container div a width. It doesn’t matter if it’s static or a percentage. This should not be a restriction for any design thankfully. The final code is below: