XML technologies / CSS / Advanced websites with CSS / A three-column layout / Our new layout with float

(Excerpt from “CSS − Advanced websites with Cascading Stylesheets” by Rachel Andrew & Dan Shafer)

Having seen in a simple example how the property float creates a multicolumn layout, we will now apply this technique to our page.

First adjust the document, moving both sidebars before the main area.

<body>
  <div id="wrapper">
    <div id="header">
     ...
    </div> <!-- header -->
    <div id="main">
      <div id="sidebar">
       ...
      </div> <!-- sidebar -->
      <div id="sidebar2">
       ...
      </div> <!-- sidebar2 -->
      <div id="content">
       ...
      </div> <!-- content -->
    </div> <!-- main -->
    <div id="footer">
      <p>Copyright 2006 - All Rights Reserved</p>
    </div> <!-- footer -->
  </div> <!-- wrapper -->
</body>

Use the file floatexample.css from the preceding example as the stylesheet’s starting point, and copy the remaining rules into it. First locate the declarations positioning the different page areas.

#sidebar {
  float: right;
  width: 220px;
  border: 1px solid black;
  background-color: #dddddd;
}
#sidebar2 {
  float: left;
  width: 159px;
  border: 1px solid green;
  background-color: #99ff99;
}
...
#footer {
  clear: both;
  border: 1px solid red;
  background-color: #ff9999;
}

Then replace the positioning settings in the file styles.css (all properties position, top, left and right) with the declarations float and clear.

#sidebar {
  float: right;
  width: 220px;
  background-color: #256290;
  margin: 0;
  padding: 0;
  color: white;
}
#sidebar2 {
  float: left;
  width: 159px;
  border-top: 1px solid #b9d2e3;
  border-left: 1px solid #b9d2e3;
  border-bottom: 1px solid #b9d2e3;
  background-color: white;
  color: black;
  margin: 0;
  padding: 0;
}
#footer {
  width: 100%;
  border-top: 1px solid #b9d2e3;
  border-bottom: 1px solid #b9d2e3;
  margin-top: 10px;
  clear: both;
}

Finally, remove the rules for position, top and left from the declarations of the element div identified as #main. Recall that this area was positioned with the rule position: relative to create a positioning context for the sidebar. Since the sidebar no longer needs it, remove that rule.

#main {
  margin-top: 10px;
  width: 100%;
}

The following figure shows that these changes arrange the page areas correctly.

The sidebars float right and left using float

Figure: The sidebars float right and left using float.

The page should ultimately look exactly like our original absolutely positioned layout. However, the footer always appears at the end and spans every column, regardless of how much content the sidebars or main area contain. The following figure shows the page in Internet Explorer.

The layout in Internet Explorer 6

Figure: The layout in Internet Explorer 6.

  

 

 

 

back to top