CSS Floating

CSS Positioning can take a while to master how to do it well, but the basics are not too complicated. There are a few different techniques for positioning including

  • Absolute Positioning
  • Relative Positioning
  • Floating

Knowing when to use which one can take time to learn, but as a general rule, floating is used to position your major content areas on the page (think making a two or three column layout).

Floating

This method allows you to “float” an element to the left or right of the page.

The Rules

If you follow these rules then things are simpler:

  1. Use classes to identify floated elements. <div class="foo">
  2. Give the class a width — width: 200px;
  3. Float it left or right — float: left;
  4. If you don’t want a block element after a floated element to also float, then apply a clear — clear:both;
  5. It usually helps to wrap a set of floated elements in a div, article or section element.

Let’s look at rule #1, #2 and #3 first and then we will get to #4 and #5.

Basic Floating

To follow rules #1, #2 and #3 we need to give an element a class, then add width and float to that class.

HTML

<div class="myFloat"></div>

CSS

.myFloat{
    width:200px; /*units can be % or em but width must be set */
    float:left;
}

And that’s it. You can add this same class to another element to float it as well, or add new classes and give them different widths and floats.

Clearing

Don’t forget to clear the enxt block element. Here is an example HTML:

<!-- this is floated -->
<div class="image"></div> 

<!-- also floated -->
<div class="description"></div> <!-- end description -->

<!-- not floated -->
<footer></footer>

and here is the CSS

.image{
    width:40%;
    float:left;
}
.description{
    width:40%;
    float:right;
}
footer{
    clear:both;
}

Leave a Reply