CSS Floating and Positioning

TOC

Floating and positioning are the CSS tools you can use to go beyond styling and coloring text with backgrounds, font changes. Floating and positioning allow you to simplify page structure coding and get rid of all those 1990s-style nested tables to arrange blocks of content. Using CSS positioning, you can also reduce page code up to 70% over using tables, depending on the layout.

Floating

Floating means pulling an element out of the normal stream of document content, and allowing the document content to “flow around” it. You have probably done this in the past with the “align” attribute in the image tag, like so: <img src="picture.gif" align="right">. This causes an image to float to the right and allows other content (such as text) to flow around to the left of the image.

In the past it was only possible to float image tags. With CSS1, however, we can now apply this attribute to any element with the float property. The float property can have values of “left”, “right”, “none”, and “inherit”. The default value for all elements is “none”. But, for example to float an image to the left, you could use this markup:

<img src="picture.gif" style="float: left;" alt="picture" />

Style sheets succeeded as a designer’s last, best hope for structure. It was a dawn of the second age of web browsers. CSS1 takes the first important steps towards sane markup and accessibility.

A floated element is removed from the normal flow of the document, but it still affects the the layout. They exist on their own CSS plane, yet they still have influence over the rest of the document.

When an element is floated, other content flows around it. This is true whether the floated element is an image, a paragraph or other element, such as a <div></div>. You can see this below, due to the margin added to the floated paragraph:

p.aside {float:right; width:17em; margin:0 1em 1em; padding:0.25em; border:1px solid;}

So we browsed the shops, buying here and there, but browsing at least every other store. The street vendors were less abundant, but much more persistent, which was sort of funny. Robin was fun to watch too, as she haggled with various sellers. I don't think we paid more than two-thirds the original asking price on anything!

Of course, we found out later just how badly we’d done. But hey, that's what tourists are for.

All of our buying was done in shops on the outskirts of the market area. The main section of the market was actually sort of a letdown, being more expensive, more touristy, and less friendly, in a way. About this time I started to wear down, so we caught a taxi back to the Touvelle House.

Floating paragraph

You usually must give a floated element a width, unless (as is the case with images) the width is implicit in the element. The reason for this is that according to CSS specifications, widths of floated elements tend toward zero.

Margins around floated elements do not collapse. If you float an image with 20-pixel margins, there will be at least 20 pixels of space around that image. If other elements adjacent to the image--and that means adjacent horizontally and vertically--also have margins, those margins will not collapse with the margins on the floated image, as you can see here:

p img {float:left; margin:10px;}

So we browsed the shops, buying here and there, but browsing at least every other store. The street vendors were less abundant, but much more persistent, which was sort of funny. Robin was fun to watch too, as she haggled with various sellers. I don’t think we paid more than two-thirds the original asking price on anything!

All of our buying was done in shops on the outskirts of the market area. The main section of the market was actually sort of a letdown, being more expensive, more touristy, and less friendly, in a way. About this time I started to wear down, so we caught a taxi back to the Touvelle House.

Floating images with margins

It is important to understand the concept of the containing block. A floated element’s containing block is the nearest block-level ancestor element. Therefore, in the following markp, the floated element’s containing block is the paragraph element that contains it:

<h1>Test<h1/>
<p>
This is paragraph text, but you knew that. Within the content of this
paragraph is an image that’s been floated.
<img src="testy.gif" style="float:right;" />
The containing block for the floated image is the paragraph.
</p>

Also, note that a floated element generates a block box, regardless of the kind of element that it is. In other words, the floated element becomes a block-level element regardless of what it was originally. So, if you float a link, even though the element is inline and would ordinarily generate an inline box, it generates a block box when floated. It will be laid out and act as if it were, for example, a div. This is similar to declaring display:block in the CSS for the floated element, although it is not necessary to do so.

Specific rules apply to floated elements, that prevent them from floating out of their containing blocks, floating on top of each other, and floating to the top of the document. There are also rules for keeping floated elements in the context with which they are associated. The higher the version of the browser you are using, the closer to compliance with these rules it should be. Often, though, different browsers and versions will implement some rules differently. As always, you must test on the browsers you expect your audience to use.

I will not go into these rules in depth here. It is easier and more interesting for you to try out floating elements and see what happens when you place them in different locations in your documents. For more details, see “Cascading Style Sheets, The Definitive Guide”; Eric A. Meyer (O‘Reilly).

There are some exceptions to the rules made to accomodate the wishes of designers. For instance, using negative margins, you can force a floated element to appear out of the boundary of its containing block, or wider than the parent, even though this contradicts some of the basic rules. Use this technique carefully -- it can also cause the floated element to overlap content outside the parent block, whose dimensions it respects.

Clearing

Tall floating elements may extend below the content of their parent blocks. In this case there may be interference with following content. To prevent overlapping or displacing of following elements, use the clear attribute in conjunction with the first element following a block containing a float. For example, to make sure all h3 elements are not placed to the right of left-floating elements you would declare h3 {clear: left;}. This can be translated as “make sure that the left side of an h3 is clear of floating images,” and is equivalent to the HTML construct <br clear="left">.

Positioning

Positioning allows you to define exactly where element boxes will appear relative to where they would ordinarily be--or relative to a parent element, another element, or even to the browser window itself.

Basic Concepts

Type of Positioning

There are four types of positioning:

static
The element’ box is generated as normal. Block-level elements generate a rectangular box that is part of the document’s flow, and inline-level boxes cause the creation of one or more line boxes that are flowed within their parent element.
relative
The element’s box is offset by some distance. Space and shape are preserved.
absolute
The element’s box is completely removed from the flow of the document and positioned with respect to its containing block, which may be another element in the document or the initial containing block. Space it would have occupied is closed up, as if the element did not exist. The positioned element generates a block-level box, regardless of the type of box it would have generated if it were in the normal flow.
fixed
The element’s box behaves as though it was set to absolute, but its containing box is the viewport (browser window) itself.

Containing Blocks

With positioning, the situation of containing blocks is somewhat different than for floating:

It is important to remember that elements can be positioned outside of their containing block, similar to the way in which floated elements can use negative margines to float outside their parent’s content area. This suggests that “containing block” should really be “positioning context”.

Offset Properties

Positioning schemes relative, absolute, and fixed use four distinct properties to describe the offset of a positioned element’s sides with respect to its containing block. These offset properties are the big part of what makes positioning work.

Each of these properties, top, right, bottom and left, describe an offset from the nearest side of the containing block. For example, top describes how far the top margin edge of the positioned element should be placed from the top of its containing block. In the case of top, positive values move the topmargin edge of the positioned element downward, while negative values move it above the top of its containing block. Similarly, left describes how far to the right (for positive values) or left (for negative values) the left margin edge of the positioned element is from the left edge of the containing block, and so on.

Remember that the offset properties define offsets from the analogous side (e.g., left defines the offset from the left side) of the containing block, not from the upper left corner.

Designing With Floating and Positioning

A common page format consists of a header area for your logo and slogan or search form, a left column for site navigation and a main column for initial content. Here we see the layout using tables to create a centered page to present the content within self-adjusting margins:

Web page:Markup:

.: Header Area :.


Nav

Link

Area

 

Article Title

The main content area. Use this to contain your introduction to the site, a PHP-fed blog column, or a front page to a store.

<html>

<head>
  <title>Tabled Layout</title>
</head>

<body>

<table>
<tr>
<td colspan="3">
<hr />
<h3>.: Header Area :.</h3>
<hr />
</td>
</tr>
<tr>
<td valign="top" style="background:#eeeeff;
padding:1em;"> <p><a href="#">Nav </a> </p> <p><a href="#">Link </a> </p> <p><a href="#">Area </a> </p> </td> <td valign="top"> </td> <td valign="top"> <h4>Article Title</h4> <p> The main content area. Use this to contain
yourintroduction to the site, a PHP-fed blog
column, or a front page to a store. </p> </td> </tr> </table> </body> </html>

Now we’ll do the same page in CSS/XHTML. Note that the markup includes a link to an external stylesheet named layout.css, which contains the following rules:

#xtopheader {
  border-top:1px solid #666;
  border-bottom:1px solid #666;
  padding:1em 0;
  }
#xnavcolumn {
  float:left;
  width:20%;
  background:#eef;
  padding:1em 0;
  }
#xnavcolumn a {
  display:block;
  margin: 1em;
  }
#xmaincolumn {
  width:75%;
  }
Web page:Markup:

.: Header Area :.

Article Title

The main content area. Use this to contain your introduction to the site, a PHP-fed blog column, or a front page to a store.

<html>

<head>
  <title>Tabled Layout</title>
<link type="stylesheet" src="layout.css" />
</head>
<body>

<h3 id="xtopheader">.: Header Area :.</h3>
<div id="xnavcolumn">
<p>
<a href="#">Nav </a>
<a href="#">Link </a>
<a href="#">Area </a>
</p>
</div>
<div id="xmaincolumn">
<h4>Article Title</h4>
<p>
The main content area. Use this to contain 
your introduction to the site, a PHP-fed blog
column, or a front page to a store. </p> </div> </body> </html>

Observe how the id attributes of the h3 and div elements in the markup select their rules in the stylesheet. To position the nav and main content columns, we simply floated the nav column left, and specified appropriate widths. Positioning scheme relative is the default, so we didn’t have to specify. The floated div’s containing box is the body of the document.

The markup in this simple example does not save all that much code. But consider that having the stylesheet external, and used in multiple pages, the slight efficiency is multiplied, since the stylesheet is cached by the browser and only downloaded once. The other improvement is that it is much easier to locate and update the content in the CSS/XHTML version, due to the elimination of all the multiple tr and td elements.

More examples

As you visit sites on the web, view the source of the ones that appeal to you. There is nothing wrong with trying out techniques you see.

Have a look at the CSS design and code techniques published at A List Apart, Glish.com, MeyerWeb.com, and the many tutorials and examples at HTMLDog.com.

Here are some workable examples of CSS positioning and styling for interesting location and box effects:

<< Colors and Backgrounds | Index