Prevent floated content extending beyond main content.

A common design for web pages is to have main content and a sidebar. Often, CSS is used to float the sidebar or the main content (or both) so that they can sit next to one another. Because floats are outside of normal page flow, this can lead to a problem whereby the area with most content sticks out below the one with less content, messing up the layout of the page.

To fix this, place a div containing a comment after the floated content and have it clear the floated content.

<html>
  <head>
    <style type="text/css">
      #container {
        background: yellow;
      }
      #sidebar {
        float: right;
      }
      #clearer {
        clear: both;
      }
    </style>
  </head>
  <body>
    <div id="container">
      <div id="main">
        <p>Main content.</p>
      </div>
      <div id="sidebar">
        <p>Some sidebar content.</p>
        <p>Some more sidebar content.</p>
      </div>
      <div id="clearer">
        <!-- Nothing here -->
      </div>
    </div>
  </body>
</html>

Last modified: 22/05/2008 Tags: (none)

This website is a personal resource. Nothing here is guaranteed correct or complete, so use at your own risk and try not to delete the Internet. -Stephan

Site Info

Privacy policy

Go to top