Looking for the lessons? Get started!
Short description of page contents.
The entire Web Design Principles section can be accessed through the menu below.
Unfortunately, not everyone's browser will support the spiffy JavaScript menu behind that innocent-looking button. If your browser won't display the menu, just click on the button and you'll be taken to a separate page with the entire menu displayed in clear, non-JavaScript HTML.
Floated elements exist outside the normal document flow, which is a fancy phrase that basically says that the order an element appears in the source code determines where it should appear on the final rendered page… — Rob Glazebrook
The idea of the float can be confusing. As Web designer and CSS instructor Rob Glazebrook says above, the float exists outside of the normal flow of the Web page. In other words, the rest of the page wants to "flow" around the floated element. So the float doesn't behave like most positioning protocols.
Glazebrooks elaborates:
Floats are different. They leave the document flow and the space they take up is reserved like in a relatively positioned element, but that space moves with the element. The normal document flow then does what it can to flow around that element. If the content following the float will fit beside it, it will do so.
To add to the confusion, floated elements are technically block-level elements, but they behave more like inline elements — they don't behave like block elements by taking up a line of their own in your document. Eek!
More about block and inline elements.
Confused? A video might help: check out Chris Coyier's screencast, aptly titled "All About Floats".
Floating Images
Probably the easiest way to use floats is with an image. And, it's a good place to give an example that might help make some sense of this. Let's try something.
This image is presented "as is", without a float, just above this paragraph text. See how the text aligns itself underneath?
This happens because the img
element is a block-level element, and must sit on its own line. Not too cool an effect with the text riding beneath the image.
What if we want to have the text flow around the image? A float will give us what we want.
This image uses the float: left
property to force the paragraph text to flow around the image. Nothing in the HTML has changed, we've just added a single line to our CSS rule. (Okay, I cheated in this example by using a div and inline styling to achieve this effect! But it will work for you.)
Here's an example of how you could style this image:
img.floatleft { float: left; }
Note that I've given a class name of floatleft
and have set it so that it only works on an image.
See how the text hugs the side of the image? Add a bit of breathing room with a margin property:
Ahh, that margin provides a nice bit of room for the text. The rest of this is just filler text to show how it continues to flow around the image within this nicely bordered div we're using for the examples. Pretty slick, huh? (Remember, the div and the border are just here for the examples, they won't appear through the use of the code I've provided.)
And here's the code:
img.floatleft { float: left; margin: 4px; }
More about margins and padding.
Floating Images to the Right
Want to float your image to the right instead of the left? Easy, just change one word in your CSS:
Now that right float provides a nice break in the normal, left-aligned flow of your document. (As I noted above, the div and the border are just here for the examples, they won't appear through the use of the code I've provided.)
And here's the code:
img.floatright { float: right; margin: 4px; }
Making the two floats work together is just a matter of placing them properly within your HTML code. This:
<img src="images/sunset.jpg" class="floatleft" alt="" title=""> <p>Filler text to show how this all works together. Boy, it's a nice day out there, isn't it? That sunset looks gorgeous.</p> <img src="images/sunset.jpg" class="floatright" alt="" title=""> <p>Filler text to show how this all works together. Boy, it's a nice day out there, isn't it? That sunset looks gorgeous.</p>
gives us this:
Filler text to show how this all works together. Boy, it's a nice day out there, isn't it? That sunset looks gorgeous.
Filler text to show how this all works together. Boy, it's a nice day out there, isn't it? That sunset looks gorgeous.
You have two distinct float options: left and right. You use margins, padding, and/or borders to give some space and room between the floated element and the content flowing around it.
There actually are five float values:
- left
- right
- both (the most commonly used value)
- none (the default, ensuring the element will not float), and
- inherit (assumes the float value from that element's parent element, and unsupported by Internet Explorer)
Glazebrook gives some more elaborate, and well-explained, examples on his site.
And veteran Web developer and tutor Chris Coyier adds some lucid explanations and illustrative examples of his own on his site. He even provides a screencast for the visually oriented among us.
Using the Clear Property
Say we want to "stack" two images atop one another in a vertical alignment. We can't do this:
<img src="images/sunset.jpg" class="floatright" alt="" title=""> <img src="images/sunset.jpg" class="floatright" alt="" title=""> <p>Filler text to show how this all works together. Boy, it's a nice day out there, isn't it? That sunset looks gorgeous.</p>
because we'll just get this:
Filler text to show how this all works together. Boy, it's a nice day out there, isn't it? That sunset looks gorgeous.
We want them vertical, not horizontal, in their alignment.
To do this, we have to add a property to our floatright
CSS rule, the clear
property.
Clear does just what it says: it "clears" a float and "resets" the document flow back to normal. (Coyier calls clear the "sister property" to float.)
If we add this line to our floatright
class:
img.floatright { float: right; margin: 4px; clear: right; }
we get the effect we wanted:
Filler text to show how this all works together. Boy, it's a nice day out there, isn't it? That sunset looks gorgeous. I have to add some more filler text to make the text fill up the space that the images take up, so be aware of that little caveat. Wow, I really have to add a lot of text. I can just blither on, thoughtlessly, listening to my music, wondering what my wife's up to, deciding whether to move my cat from where he's lying on my shoes…
See how that clear: right
property works? It disallows any "carryover" floats from the right side.
Naturally, you have other options besides a value of right. Here's a list:
- right
- No floating elements allowed on the right side
- both
- No floating elements allowed on either the left or the right side
- none
- Default. Allows floating elements on both sides
- inherit
- Specifies that the value of the clear property should be inherited from the parent element
Easy Clearing Methods
There are quite a few methods for clearing floats. It isn't always practical to add a clear property to a particular CSS rule, so sometimes you have to improvise. Chris Coyier gives a number of alternatives, and SitePoint's Paul O'Brien and Alex Walker give a a fiendishly simple method that works quite well, but the following dirt-simple method works in most instances.
Basically, you'll add an empty div to your HTML code, with a CSS class attached that clears the floats. Here's the HTML:
<div class="clearboth"></div>
and here's the CSS:
.clearboth { clear: both; }
People who insist on purely semantic HTML object to this method, because empty divs are not semantic. They make a strong argument that such a method is not best practices, and I won't say they're wrong. However, as Coyier notes:
This method is scorned by semantic purists since its presence has no contexual meaning at all to the page and is there purely for presentation. Of course in the strictest sense they are right, but it gets the job done right and doesn't hurt anybody.
I say go ahead and use it.
The more advanced designers out there will be interested in Jeff Starr's article on the "clearfix hack".
Floats in Layouts
Using floats to position images is relatively easy. When you begin using floats to create page layouts, that's stepping it up a notch.
They're most commonly used to create left-aligned sidebars:
#sidebar { float: left; }
and right-aligned main content sections:
#maincontent { float: right; }
(Of course, nothing's wrong with a right-aligned sidebar and a left-aligned main content section!)
If you want a footer below the sidebar(s), main content areas, and whatever other layout elements you've created, clear comes in handy:
#footer { clear: both; }
Collapsing Floats
For reasons that are too abstruse for me to fully comprehend, sometimes floating elements can cause portions of your layout to "collapse".
Basically, what happens is that if a "parent" element contains nothing but floated "child" elements:
More about parent-child relationships in CSS.
then the height of that parent element collapses to zero.
(Image used pending permission from Chris Coyier. If Chris says no, I'll have to do battle with Photoshop to provide something similar.)
The HTML code might look something like this:
<div class="container"> <img src="image1.png" class="floatleft" alt="" title=""> <img src="image2.png" class="floatleft" alt="" title=""> <img src="image3.png" class="floatleft" alt="" title=""> </div>
You might not even notice the difference if that parent element has no visual content, i.e. a background image/color or text, but it's something to avoid nevertheless.
How to deal with it? Clear the float after the floated elements but before the close of the container. Like this:
<div class="container"> <img src="image1.png" class="floatleft" alt="" title=""> <img src="image2.png" class="floatleft" alt="" title=""> <img src="image3.png" class="floatleft" alt="" title=""> <div class="clearboth"> </div>
Note: Valkhof recommends adding overflow:auto;
to the containing element's CSS rule.
Internet Explorer Bugs
A lot of designers are leery of working too extensively with floats, largely because of a slew of perplexing and frustrating IE bugs that plague that browser. Coyier gives us a quick breakdown of some of the most annoying of IE6 bugs, and quick fixes for them.
Pushdown: When an element inside a floated item is wider than the float itself (usually an image), most browsers put the image outside the float, and compensate for the excess part affecting the rest of the layout. Not IE: it expands the float to contain the image, often breaking the layout (i.e. shoving the sidebar down. Quick fix: Make sure you don't have any images that do this, and use the overflow: hidden
property to cut off excess.
Double Margin Bug: If you apply a margin in the same direction as the float, IE6 doubles the margin. Why? Who knows? Quick fix:set display: inline
on the float (it's okay, the float will remain a block-level element). Rob Glazebrook gives a more detailed examination of the double-margin bug. Check out the John Gallant article if you're really curious about it.
3px Jog: When text is alongside a floated element, the text gets shoved aside by 3 pixels. Coyier writes that this effect is "like a weird forcefield around the float." Quick fix: set a width or height on the affected text.
Bottom Margin Bug: In IE7, when a floated parent element has floated children inside it, the bottom margin on those children is ignored by the parent element. Quick fix: use bottom padding on the parent instead.
I'm not sure why, but Coyier leaves out the equally annoying Peekaboo Bug. That one was quashed in IE7, but if you're coding for IE6 (and most of us still do), you have to deal with it. Basically, IE hides content that is supposed to appear beside a floated element (i.e. an image). You reload the page, and nothing happens. You scroll down the page, or click to another tab or window, and when you return, the content is there. Augghh! There are three not-so-quick fixes to this, as documented by John Gallant: keep the clearing div from touching the float or avoid using a background on the element containing the float (not too hot); use position: relative
on both the containing element and the floated element (not always feasible); or trigger IE's hasLayout property. The third one is the best, but IE's hasLayout makes my head hurt trying to understand its quirks. Check the link for information and solutions.