Developer

Build a better Web site by understanding floated elements in CSS

One of the most important concepts a Web developer can understand about CSS are floated elements, which serve a valuable function in aligning and positioning elements relative to each other on a Web page. A brief introduction to these floated elements is presented, explaining the CSS float and clear directives and providing some examples of how you can use them to better position HTML elements on a Web page.

This article is also available as a TechRepublic download, which includes the code listings in a more manageable text file format.

Cascading Style Sheets (CSS) are rapidly becoming the de facto standard for Web page layout and positioning. They're easy to use, don't require any special software, and work uniformly on most major browsers. Using them correctly, however, requires a sound analysis of the functional purpose of a particular layout, both to ensure that the resulting style sheets are logically and functionally correct and that they are portable across different browsers or viewing devices.

Often, Web developers fail to understand this particular aspect of style sheet usage, leading to code that contains numerous "hacks" to produce the desired end result. To mitigate this problem, it is worth spending some time to understand some of the core CSS drivers and concepts. And one of the most important concepts a developer can understand are so-called floated elements, which serve a valuable function in aligning and positioning elements relative to each other on a Web page.

This article provides a brief introduction to these floated elements, explaining the CSS float and clear directives and providing some examples of how you can use them to better position HTML elements on a Web page.

Floating elements

Essentially, an element that has the float property applied to it moves out of the normal flow of a page, "floating" in space such that content wraps around it. Thus, an element that is floated to the left will have text running down its right side and wrapping around its bottom edge; an element floated to the right will have content running down its left side.

The float property can take one of three possible values: left, which floats the element to the left; right, which floats it to the right; and none, which eliminates floating. Applying the float property to an element automatically turns it into a block-level element. Other non-styled elements ignore the float, acting as though it doesn't exist. If a float bumps into another float generated previously in the document and on the same side, it must remain either to the right of the previously-generated float (if sufficient space exists) or below it (if insufficient space exists).

Example 1: Wrapping text around an image

To better understand floats, let's consider a simple example: using the CSS float property as a replacement for HTML's ALIGN attribute. Consider the following example (Listing A), which floats an image to the left such that descriptive text wraps around it:

Listing A

<html>
<head>
    <style type="text/css">
    .floater {
        float: left;
        border: solid 1px black;
        padding: 5px;
        margin: 5px;
        width: 100px;
        height: 75px;
    }
    </style>
</head>

<body>

<img class="floater" src="pix2180.jpg" />

Loremipsum dolor sit amet, consecteturadipisicingelit, sed do eiusmodtemporincididuntutlabore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteursintoccaecatcupidatat non proident, sunt in culpa qui officiadeseruntmollitanim id estlaborum. Loremipsumdolor sitamet, consecteturadipisicingelit, sed do eiusmodtemporincididuntutlabore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.

</body>
</html>

Figure A shows you what it looks like.

Figure A

Example 1: Wrapping text around an image

In this case, the image is floated to the left, causing the content that follows to flow down its right side and then wrap around below it. Further, as you resize your browser window, the size of the "box" holding the text will dynamically adjust to the new dimensions.

Example 2: Two-column layout with images at either end

Let's take it a little further, by creating a two-column catalog layout wherein each column contains both an image and some textual content (Listing B). To make things interesting, let's set it up so that the image is left-aligned in the left column, and right-aligned in the right column.

Listing B

<html>
<head>
    <style type="text/css">    
    div {
        width: 48%;
        padding: 5px;
    }
   
    img {
        padding: 5px;
        margin: 5px 15px 5px 5px;
        width: 100px;
        height: 75px;
    }
     </style>
</head>

<body>
<div style="float: left">
<img style="float: left" src="pix2180.jpg" />
Loremipsum dolor sit amet, consecteturadipisicingelit, sed do eiusmodtemporincididuntutlabore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteursintoccaecatcupidatat non proident, sunt in culpa qui officiadeseruntmollitanim id estlaborum.
</div>

<div style="float: right">
<img style="float: right" src="http://www.melonfire.com/account/tools/ig/galleries/Places/Greece/Santorini/IMG_2180.JPG" />
Loremipsum dolor sit amet, consecteturadipisicingelit, sed do eiusmodtemporincididuntutlaboreetdolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteursintoccaecatcupidatat non proident, sunt in culpa qui officiadeseruntmollitanim id estlaborum. 
</div>

</body>
</html>

With floats, this isn't particular difficult to do: simply create two <div>s, one for each column, and place within each one a floated image and some text. Next, float the <div>s themselves, one to the left and the other to the right. Figure B shows you what the result looks like.

Figure B

Example 2: Two-column layout with images at either end

Clearing Elements

A companion to the float property is the clear property, which actually controls the position of the element(s) following a float. This property can be used to prevent content from flowing along a floated element, forcing it to the next line below a float.

The clear property can take one of four possible values: left, which pushes the element to below any previously-generated left-floated elements; right, which does the same for right-floated element; both, which moves it below all previously-generated floats; and none, which removes any previous positioning. Interestingly, the clear property is not restricted to non-floated elements only, as one might suppose; rather, it can be used to control the behavior of floated elements as well, by pushing one floated element below another.

Example 3: Vertical image column with wrapped text

To see this in action, consider the following example (Listing C), which produces a set of images in a vertical column through creative use of the float and clear properties.

Listing C

<html>
<head>
    <style type="text/css">
    .floater {
        float: left;
        clear: left;
        border: solid 1px black;
        padding: 5px;
        margin: 5px 15px 5px 5px;
        width: 100px;
        height: 75px;
    }
    </style>
</head>

<body>

<img class="floater" src="pix2180.jpg" />
<img class="floater" src="pix2181.jpg" />
Loremipsum dolor sit amet, consecteturadipisicingelit, sed do eiusmodtemporincididuntutlabore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteursintoccaecatcupidatat non proident, sunt in culpa qui officiadeseruntmollitanim id estlaborum. Loremipsumdolor sitamet, consecteturadipisicingelit, sed do eiusmodtemporincididuntutlabore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.

</body>
</html>

Here, both images are floated to the left, and the use of the clear:leftproperty on the second image ensures that it is pushed below the first image, creating a vertical column. Note that the same clear property applies to the first image, but has no effect because there is no content above this image. The use of the float property also ensures that the block of text on the page (which, importantly, is unstyled) wraps around the image column.

Here's what it looks like (Figure C).

Figure C

Example 3: Vertical image column with wrapped text

Of course, these three examples are just the tip of the iceberg when it comes to working with floated elements. There are many more layout possibilities and clever interface designs that are possible with the float and clear properties. However, the examples above should have given you some insight into how these properties work in practice, and you should now know enough to begin experimenting on your own. So what are you waiting for? Get started —- and happy coding!

Editor's Picks

Free Newsletters, In your Inbox