Understanding CSS floats

In my designs, I tend to use floats, as opposed to relative/absolute positioning, as I find it gives a design more power and a greater ability to scale vertically.

When I first approached CSS I couldn’t for the life of me understand how floats worked. My main struggle was trying to comprehend why floating something to the left or right led to so many other items being disrupted and not being cleared.

Then one day, on a forum, someone explained floats very simply and suddenly, I understood. Floating an item affects the other items around it more so than the floated item. So if you make an image float: right then what you are really doing is floating every else to the left and under the image. Hence why items don’t clear unless you specify them to as they are floating up next to the image.

Usually, floats are explained as being taken out fo the document flow – which meant nothing to me and sounded like gibberish when I was learning CSS.

Float everything

Once you begin floating items, you will end up floating everything. If you use floats on your form elements (e.g inputs, label, textareas, etc) and don’t float the form or fieldset then they won’t stretch to the full length of the form and cause havoc if you add a background image/colour to them.

Similarly if you float a navigation area and a content area next to each other then you’ll probably have to float your containing div and maybe even the body tag to make sure everything stretches to full height.

I don’t see that as a particular problem but some do and get enormous problems with floats culminating with them using contrived clearing methods like:

<br style="clear: both" />

There isn’t a need for this with good CSS – just float most parental div blocks if a good number of their children are floated and remember to clear items below.

Code tips:

Floating an image

img{
float: left;
margin: 0 1em 1em 0; /* adds some white space around the image */
}

Clearing a header

h3{
clear: both;
}

One response to “Understanding CSS floats”