How to – layout with fixed sidebar

Today I was working on a page layout where a page width had to be fluid, while the sidebar had to be with fixed width. So here is my solution:

The layout looked like this in the beginning:

Layout


HTML:

<body>
  <div class="wrapper">
    <div class="sidebar">
       <!-- some content -->
    </div>
    <div class="main">
       <!-- some content -->
    </div>
  </div>
</body>

CSS:

.wrapper{width: 90%; margin: 0 auto;}
.main{margin-right: 300px;}
.sidebar{float: right; width: 260px;}

Everything works perfect until you don’t have any special code which need to be placed inside the main container and formatted in a special way. In my case it was a horizontal menu, but it could be anything.

So the final result looked like this:

Layout 2

HTML:

<body>
  <div class="wrapper">
    <div class="sidebar">
       <!-- some content -->
    </div>
    <div class="main">
       <div class="fix"> <!-- the extra div -->
          <!-- some content -->
       </div>
    </div>
  </div>
</body>

CSS:

.wrapper{width: 90%; margin: 0 auto;}
.main{margin-right: 300px;}
.sidebar{float: right; width: 260px;}
.fix{float: left; width: 100%;} /* extra class */

So, what is the difference?

If you have elements which are floated (like the horizontal list) you need to clear the rest of the elements (the paragraphs), because otherwise the paragraphs will wrap the horizontal menu.

But if you set clear:both to paragraphs, then the paragraphs will go under the end of the side bar and there will be large gap between the menu and the content. Here comes the fix container – it’s aligned left and with width 100%. This way all elements inside it are not related with the side bar and can be cleared properly.

This is not a rocket science, and probably it was written in many other sources, but because it’s handy, I decided to share it with you. I’ve tested it in all modern browsers (even IE6) and it was working as expected.

Here is the working example

Hope this helps someone.

Leave a Reply

Your email address will not be published. Required fields are marked *