CSS: float layout tutorial

Creating a CSS layout with floats could seem simple to advanced CSS users but not so simple to beginners. This tutorial aims to cover the basics for allowing you to create a simple CSS layout with floats. I'll follow a step-by-step approach to make things easier for you. For now, let's start with our HTML structure:

<div id="site">

  <div id="header">...</div>
  
  <div id="content">
  
    <div id="main">...</div>
    <div id="content-sub">...</div>
  
  </div>
  
  
  <div id="footer"></div>


</div>

Our final layout should look like this:

We have a two-columns layout with header and footer. We're not interested in the header and footer because they're simple static elements. Instead, we're more interested in what happens in the content area. Let's move on.

Step 1: preparing the content area for floats

First, we need to center our content area and make sure that floats will remain contained within it. Here's the code:

#content {
 width: 80%;
 margin: 0 auto;
 padding: 1.5em 0;
 overflow: hidden;
 height: 100%;
}

The element has been centered thanks to horizontal automatic margins. Floats have been contained by using the overflow: hidden statement. height: 100% is used here for backward compatibility with Internet Explorer 6.

Step 2: creating the columns with floats

When setting up floats, bear in mind that the sum of their widths shouldn't never be greater than the width of their container. If you specify a greater width, then one of the floats will be pushed down to the next line, because there's no more horizontal space available.

#main {
 float: left;
 width: 70%;
}

#content-sub {
 float: right;
 width: 30%;
}

70% plus 30% is 100%, so our float dimensions will fit the global width of their parent (which is 100%). There's nothing more to say except that you should always remember the box model theory, that is, if you add margins, borders and paddings these will be added to the width of your elements.

Did you expect more steps? Sorry to disappoint you. wink

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.