Looking for the previous guiStuff?

It's still here, the content didn't go anywhere. You may want to check out this new guiStuff though -- It's rather informative.

References/Tutorials:


Intro Documents:


guiStuff:









::Stuff for the multi-spec coder;

Coding, formats, standards, and other practical things.

 Home  //  CSS Articles  //  Floating Elements 

<!-- CSS Articles

Floating Elements

A commonly misunderstood, and highly underrated property of CSS is the float property. The ability to float elements has been around since earlier in HTML's life, but has been cemented in CSS in terms of rules of implementation, even if not all browsers implement floated elements properly when they're presented with an overly complicated scenario.
The broad definition of "float-ing" an element is that you assign that element a certain amount of the horizontal space (width) within its containing block, and tell it to allow other content to flow down the right or left edge of it, instead of it taking up all of the horizontal space that it would usually take up. The most common example is the IMG element: If you were to place text within a document, followed by a BR, followed by an image, followed by another BR, and then followed by additional text, the image would take up however much vertical space it needs, and all of the horizontal space to its right (assuming the document is left-aligned) will be wasted. If you were "to float" that image to the left, it would allow content to flow along its right edge, and the browser (or whatever happens to render the document) will take care of spacing this text for you so that it will align, wrap, and fill the area properly. But this is just one very common, very simple scenario. The float property allows you to structure many elements around the document, and is much more powerful that most people give it credit for.

The Browser Compatibility Anthem

I'll get browser compatibility out of the way before I delve into the subject, to solve the "should I even be reading this if it's not properly suppoorted across every browser ever?" question thing. Floating elements is an old trick, it's just being applied to new elements as designers/developers realize that the majority of browsers support this. It used to apply almost exclusively to images, at least in practice, and you'd see a mention every now and again that you can float "any block" (followed by sarcastic comments like "Yes! It's the World of Tomorrow!"). Today, you really can float any block, and even Internet Explorer 6 will accomodate most scenarios. If you round up IE6, IE7, Firefox, Opera, and Safari, you get around 99.8% of the browsers out there (according to current statistics). Even if there's a shift in browser usage, it's not going to be in favor of an older, less compliant browser. Whatever your views are in terms of "who's gaining" in the browser wars, it doesn't matter -- all of the latest versions of the aforementioned browsers have better support for Web Standards and it's not like one of them is going to start 'removing support' as part of its roadmap.
That said, there are always some creases, since it wouldn't be fun if things 'just worked'... However, they aren't broad enough for me to round them up in a paragraph, but rather they're scenatio-specific, which is why whenever something doesn't work along the way, in whichever browser, I'll alert the bells. You'll notice, however, that these scenarios are rather specific, easily avoidable, and hardly make floating elements any less of a powerful tool even if you were to steer clear of them completely.

Floating (verb.) elements

Let's start by clearing up what applying the float property does to the element itself. The first thing you'll notice when floating an element is that it becomes a block-level element. This isn't completely clear in the CSS 2.1 spec, but you will find that when you apply the float property to an element, all browsers, with vitrually no exceptions, will turn them into blocks. You can test this by applying properties that effect block-level elements diffently than they effect inline elements.

Here's some markup along with CSS to test this with:

<style type="text/css"> .test_properties { width:150px; background-color:#99CCFF; padding: 5px 10px 5px 10px; border: 1px solid #3E95EC; } .make_it_float { float:left; } </style> <span class="test_properties"> Magnesium is the chemical element in the periodic table that has the symbol Mg, the atomic number 12, and an atomic mass of 24.31. </span> <br /><br /> <span class="test_properties make_it_float"> Magnesium is the chemical element in the periodic table that has the symbol Mg, the atomic number 12, and an atomic mass of 24.31. </span>

Two style rules were created: test_properties was given four properties, three of which appear differently when applied to inline elements than they do when they're applied to block-level elements (these would be the background-color, padding, and border properties), and also the width property which is ignored by inline elements. The second rule, make_it_float, just applies the float property value of left to an element. Then, there are two paragraphs, one which is styled by just the test_properties class, and the other which is styled by both. Actually, when I say "paragraph", I don't mean the P element, since that element is inherently a block-level element -- I mean SPAN elements with "a paragraph of text" in them.

Now to see how the two 'paragraphs' render:

Magnesium is the chemical element in the periodic table that has the symbol Mg, the atomic number 12, and an atomic mass of 24.31.

Magnesium is the chemical element in the periodic table that has the symbol Mg, the atomic number 12, and an atomic mass of 24.31.

There would have been no difference if the second SPAN element had its display property value set to block, instead of being applied a float property. The reason for the element becoming a block when being floated has to do partially with its need to have a set width property (in fact, this is the primary reason). This, again, isn't made completely clear in the CSS 2.1 specification, but it is, this time, made clear in code implementation, rather than browser/renderer implementation. While you can apply a float property to an element without that element having a set width value, you'll simply get no consistent results. The element can have a width value either inherently as part of the element's definition, like IMG elements, some elements may have the width HTML/XHTML attribute set, or you can set the CSS width property value. Any one of these will tell the document renderer that there's either an absolute width value, or a relative width value to be calculated, but in both cases there's a value to work with in terms of absolute units after all of the calculations are done (units is a generic term here, since pixels are relevant to a display device, whereas a printing device might use dots or other types of units of measurement).
What else does applying the float property to an element do to the element itself? It aligns it either to the left, or to the right, within its containing block, depending on the value you've set. This isn't exactly like aligning elements, since it will react differently to other floating elements, for one thing, but in many cases, it will, in most respects, have the same effect.

Here's a simple example:

Containing Block: a DIV with a border and a set height.
Float A Floated: Right

To start to actually see how floating an element works with other elements, it's practical to test how it works with other floating elements of the same type. Here's what happens if you take that last element and append elements of the exact same type right after it:

Containing Block: a DIV with a border and a set height.
Float A Floated: Right Float B Floated: Right Float C Floated: Right

Note that the elements appear in the markup as Float A though Float C (Float A precedes Float B, which precedes Float C), meaning that they actually stack to the right. We'll get to the markup in a bit, right now we'll stick to the abstract so that code doesn't clutter the concepts (This would be a complete oxymoron in a programming language, to say that code "clutters" the relating of ideas, but we're talking about how a browser/renderer interprets visual definitions, which is why if I were to place markup after each example at this point in the document, it would just distract from the goal. There'll be plenty of code to work with later).

Floating objects will continue to stack until there's 'no more width' to contain them. That is, they'll keep trying to appear horizontally, aligning to whichever side they're floated to, until the containing block can no longer contain any more of them in its calculated final width. At that point, they'll go to a new line and begin again:

Containing Block: a DIV with a border and a set height.
Float A Floated: Right Float B Floated: Right Float C Floated: Right

I should note at this point, that I'm giving the example of multiple floating blocks because it is instrumental in explaining how floating elements behave. This doesn't at all mean that in order for you to have one block-level element appear horizontally after the other, that both need to be floated -- only one does. If you want to stack them horizontally, however, then you would need to, depending on how you want to arrange them, float more than one of them.

Rules of Engagement

Now let's talk implementation. You want to float an element, meaning that you want a block of content to have other element/s to flow to the left, or to the right of it, instead of it monopolizing the entire horizontal space to its right/left. There are several things that you need to consider in your implementation.

The first rule of FloatClub is...

Floating elements must have a set width. Their width may be set inherently, like in IMG elements, they could be set by the width HTML/XHTML attribute, or it may be set using the CSS width property -- but in some way, the element that's being floated must have a width to 'report' to the browser/renderer. This is the way the browser knows how much width to allocate to this element, and how much width is 'left over' for the other elements to flow through.

Above, Below, and Beyond

Floating elements allow elements that follow them (elements that come after them in the document) to flow beside them. They do not effect preceding elements (anything that came before the floating element within the document). There are actually a few exceptions to this, but they are limited, and I'll make note when they're encountered.

Ducks in a Row

Before delving into a maelstrom of examples, let's have a look at the plan of attack:

Floating

So we have a simple enough set of guidelines:
  • The floating element will be 'aligned' either to the left or the right edge of the containing block.
  • Elements that follow the floating element will 'measure' the remaining horizontal space from the floating element's available edge to the containing block's other edge.
  • If the following elements fit within this space, they will be moved upwards in the document to occupy this space. This applies to all elements that will fit within this horizontal space, until the vertical space that is equal to the floating element's height is filled.
  • At this point, elements will continue to flow as usual within the document.

Less Talk, More Markup

Let's first make up a block-level element we can play around with easily:

<style type="text/css"> .square { display:block; width:65px; height:65px; background-color:#FFCC33; border: 2px solid #FF9933; margin:5px; padding: 5px; } .float_left { float:left; } .float_right { float:right; } </style> <span class="square float_left"></span> <span class="square"></span>

The square class makes a 65px wide by 65px high square with background-color, border, margin, and padding properties out of a SPAN element easily so we can throw them around and experiment. They're assigned a display property value of block because they won't always be floating, sometimes they'll just be plain old blocks laying around.

Remember that the idea here is that this floating SPAN (you can use a DIV, it depends on what you want it to contain) can be an image, it could be holding a paragraph of text, it could contain a list, or a table, or just about any combination of elements. Obviously, it wouldn't be this size, but the idea is that you take a block-level element and float it to achieve a structural goal.

We'll also define a containing block class so we can more easily see the borders that wrap what we're containing:

.containing_block { border: 2px solid #FF9933; padding: 5px; font-size: 12px; line-height: 1.2em; width: 250px; }

Floating block followed by text

Thist is most commonly used when floating an image, but this time we're floating a generic block, so you can really replace its contents with anything:

Copper is a chemical element in the periodic table that has the symbol Cu and atomic number 29. It is a ductile metal with excellent electrical conductivity, and finds extensive use as an electrical conductor, thermal conductor, as a building material, and as a component of various alloys.


The marup for this is very simple:

<p class="containing_block"> <span class="square float_left"></span> Copper is a chemical element in the periodic table that has the symbol Cu and atomic number 29. It is a ductile metal with excellent electrical conductivity, and finds extensive use as an electrical conductor, thermal conductor, as a building material, and as a component of various alloys. </p>

If you were to apply the float_right class to the square instead, you'd get the following:

Copper is a chemical element in the periodic table that has the symbol Cu and atomic number 29. It is a ductile metal with excellent electrical conductivity, and finds extensive use as an electrical conductor, thermal conductor, as a building material, and as a component of various alloys.



You can also float a block within a paragraph. Here's an example:

Copper is a chemical element in the periodic table that has the symbol Cu and atomic number 29. It is a ductile metal with excellent electrical conductivity, and finds extensive use as an electrical conductor, thermal conductor, as a building material, and as a component of various alloys.

Tin is a chemical element in the periodic table that has the symbol Sn (Latin: stannum) and atomic number 50.


Here, the square is nested within not only the P element, but it's within the text itself. The Marpup for this is very simple, the square was just moved within the text itself:

<p class="containing_block"> Copper is a chemical element in the periodic table that has the symbol Cu and atomic number 29. It is a ductile metal <span class="square float_left"></span> with excellent electrical conductivity, and finds extensive use as an electrical conductor, thermal conductor, as a building material, and as a component of various alloys. <br /><br /> Tin is a chemical element in the periodic table that has the symbol Sn (Latin: stannum) and atomic number 50. </p>

Now suppose you have something like a list of objects, each with its own icon or thumbnail, and a short line of text under it. This is a common scenario when you're designing a control-panel-like design, or simply a list of thumbnails. Now suppose that you don't know how wide the area containing these elements will be, and in fact, that the size of these elements might change (if they're image thumbnails, you may want to give the user the ability to change their size).

That's perfect for "float-stacking":

I'm going to place some text in here that will flow, or rather 'spill', along the right side of the squares...

Now that wasn't expected... Actually, it was expected, but it wasn't what we wanted. At this point, it's time to introduce float's partner-in-crime: clear.

Clear for Takeoff

At some points, you'll want some way to tell the document renderer to stop letter content flow around a floated element. There are many reasons for this, and you'll see more of them in the following examples. You do this by using the clear property. When you apply the clear property to an element, you can choose to give it a value of left, right, or both. This tells the element not to allow content to flow around a floating object that appears previously in the document. For example, clear: left; means that if this element sees a floating element preceding it that was floated to the left, it will 'resist' flowing alongside that element, even if it does fit within the flowing space. You can imagine, then, that float: both; means that the element will stop flowing from any direction, in practice becoming a "floating stops here" element within the area of the document where it appears (because any element that follows it will follow the element with the clear property, which means that it will no longer have a floating element preceding it).

Combining float and clear will allow you to create amazing structures with ease, but let's start with the basics:

Copper is a chemical element in the periodic table that has the symbol Cu and atomic number 29.
//Stop Floating//
It is a ductile metal with excellent electrical conductivity, and finds extensive use as an electrical conductor, thermal conductor, as a building material, and as a component of various alloys.

This was a simple example of how you would use clear to stop the flow of content around a floating element. Here's the markup:

<div class="containing_block"> <span class="square float_right"></span> Copper is a chemical element in the periodic table that has the symbol Cu and atomic number 29. <div style="clear:both;"> <b><i>//Stop Floating//</i></b> </div> It is a ductile metal with excellent electrical conductivity, and finds extensive use as an electrical conductor, thermal conductor, as a building material, and as a component of various alloys. </div>

The DIV up there was styled inline, rather than having a class applied to it, which is typical if you only have just one property you want to apply. Actually, that DIV (without the text in it, of course) is something you'll see quite a bit if you go around looking through source markup of pages that float elements. This is because while you can apply a clear property to any element, it's very convenient to just have an empty DIV that 'clears floating' from a certain point onward. In other words, you could apply the clear property to the element that follows the floating element, but you never know what element that will be, and if you'd need to modify it further because of other properties it may already have.
By placing <div style="clear:both;"></div> at a location in the document, you know when you look at it what it's there for, and it's easy to maintain later if you want to make modification to your structure. You have to remember, though, that it's a DIV, which means that you're going to want to make sure you're within another DIV element to begin with (there's a simple solution to non-DIVs, I'll get to it in a moment).

Let's fix that floating stack example from earlier:

No float for you!

In the above example, the clearing DIV was placed after the last floating element, after which there's no need to worry about the floating effecting any other elements.
But what about when you're not floating an element within a DIV? A DIV is 'high up' in the element hierarchy, and without going into too much detail about how browsers render pages, we already know we can't just throw DIVs within P elements without expecting trouble, even though they're both block-level elements. No worries -- all we need is an element that's block-level, and clears both sides, so we'll make it:

<span style="clear:both; display:block;"></span>

That was the 'clearing SPAN'. You can place it within P elements, within other block-level SPAN elements, and within DIVs. So the question is, when to use a clearing SPAN and when to use a clearing DIV?... Technically, you can use the clearing SPAN anywhere and it should perform just like any of the two. However, browsers will be browsers, and so there's a simple rule you may want to follow: If you're directly within a DIV, use the clearing DIV. Otherwise, use the clearing SPAN. The reasoning is simple: If you're already within another DIV -- and by this I mean you're directly under it, not within an element that is nested within a DIV -- you know that placing a DIV won't disrupt the styling of the parent DIV.

Clearing Above

Clearing will also get you out of some interesting browser incompatibilities. Let's look at the following markup:

<p class="containing_block"> Alpha <span style="float:right;">Beta</span> <br /><br /> </p>

Here's how this renders:

Alpha Beta


If you're using anything but Opera to view this page, then the word 'Alpha' appears above the word 'Beta'. According to the CSS 2.1 Specification, the two words should appear on the same line. This is subtle, and in fact technically makes the floating element effect the element above it. According to the specification, this will only go as far as one box level above the floating element, or any of that elements descendants. That makes it very subtle, but it's still valid within the specification, and the Opera Browser implements it correctly.
This is actually unlikely to appear in upcoming browser implementations other than Firefox (Internet Explorer has a lot to go before it reaches this point of compliance accuracy), so you may think you should just let it go. But there's no reason to penalize Opera users because their browser sticks to the rules this well, especially if fixing the problem is as easy as it is: Just clear above the floating element. Yes, it's that simple -- if you clear above the floating element, you're telling any and all browsers: "I don't care about how compliant you are, I know what I want, and I especially want my page to show up the same way across all browsers!". Ok, so that was a bit broad for this specific fix... Let's rephrase -- You're telling the Opera Browser: "Don't look up.". Remember though, other browsers may implement this feature sooner than you think, so clearing above floating elements will make sure your design is future-proof in this particular respect.

Basically, you'd do this:

<p class="containing_block"> Alpha <span style="clear:both; display:block;"></span> <span style="float:right;">Beta</span> <br /><br /> </p>

It looks like this:

Alpha Beta



If you're not using Opera, you shouldn't see any difference. If you view this page using the Opera browser, the word 'Alpha' now appears above the word 'Beta', just like it does in other browsers. I should mention: If you haven't yet, Opera is free and cross-platform, so there's no reason not to go and download it for checking your pages using an additional browser. If you're designing pages and care about cross-browser compatibility, then there's no reason not to have both Firefox and Opera installed on any computer so that you can check your pages as you're designing them. Both browsers are a free download, and they both work on Windows, Mac, and Linux (and BSD, etc.). I'll even save you the typing: Firefox and Opera.



Bigger Picture

Let's wrap up by applying float and clear to a mini-document.
We'll start with the HTML/XHTML:

<div class="mini_doc"> <h3>Mini Title</h3> <p> ... A whole bunch of text... </p> <br /> <ul> <li>Copper</li> <li>Tin</li> <li>Zinc</li> <li>Antimony</li> <li>Magnesium</li> </ul> <span style="clear:both; display:block;"></span> <span>This is a Footer</span> </div>

Next, we'll setup some CSS style rules:

.mini_doc h3 { padding: 2px; border-bottom: 1px solid #888; } .mini_doc p { margin: 10px; width: 300px; float: left; padding-right: 15px; } .mini_doc span { display:block; text-indent: 2em; background-color:#CCCCCC; padding: 2px; }

Here's what we get:


Mini Title

Tin is a chemical element in the periodic table that has the symbol Sn (Latin: stannum) and atomic number 50. This silvery, malleable poor metal that is not easily oxidized in air and resists corrosion, is found in many alloys and is used to coat other metals to prevent corrosion.

Copper is a chemical element in the periodic table that has the symbol Cu and atomic number 29. It is a ductile metal with excellent electrical conductivity, and finds extensive use as an electrical conductor, thermal conductor, as a building material, and as a component of various alloys.


  • Copper
  • Tin
  • Zinc
  • Antimony
  • Magnesium
This is a Footer


That was actually one of many ways to create a table-less layout, but that's another topic altogether. The main paragraph was given a width and floated to the left, making room on its right for content to flow. The list found that room to be sufficient and flowed in, but the footer was something that needed to be kept under the whole thing, so a clearing SPAN was placed under the list. Apart from that, the heading was given a border and padding, the footer was given a background-color, padding, and text-indent. The main paragraph also had its margins overridden (a P element usually generates margins above and below, and none to the sides).

Believe it or not, this was actually tame coverage of the floating feature. There are countless ways to 'hack' the float property to achieve all sorts of amazing things, if you're willing to create different style sheets for different browsers. The information in this article should give you plenty of new structuring ideas to play with though, without having to go into grey areas. There's a lot of experimentation to be done with the float property, and checking your results in different browsers is a must in this case.

Happy Floating!



Return to the CSS Articles section, or go the to Main page.





Looking for the old guiStuff?

It's still here, the old content didn't go anywhere.