2 column layout (Left column fixed width, right fluid + clear:both)

Ondrej picture Ondrej · Jul 23, 2011 · Viewed 16.2k times · Source

Just need help as I have been trying sort this out for ages now. What I need:

I've got a 2 column layout, where the left column has a fixed width 220px and the right column has a fluid width.

Code is:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml">
 <head>
     <title>Fluid</title>
    <style type="text/css" media="screen">
        html, body { background: #ccc; }
        .wrap      { margin: 20px; padding: 20px; background: #fff; }
        .main      { margin-left: 220px; width: auto }
        .sidebar   { width: 200px; float: left; }
        .main,
        .sidebar   { background: #eee; min-height: 100px; }
    </style>
</head>
<body>
    <div class="wrap">
        <div class="sidebar">This is the static sidebar</div>
        <div class="main">This is the main, and fluid div</div>
    </div>
</body>
</html>

There's no problem at all. When I use a css syntax clear: both in the right column, all content after gets moved under the left column. This is a right behaviour and nothing against it.

But I relly need to use clear: both in the way, that it stays just in context of the right column (doesn't get affected by the left column at all, and doesn't move underneath)

Is there any simple get around with retaining a basic float concept of page design?

UPDATE: Please see this link to know what I'm on about as it may be a bit confusing from my description. Link: http://jsfiddle.net/k4L5K/1/

Answer

Karl Nicoll picture Karl Nicoll · Jul 23, 2011

Here's your altered CSS:

html, body {
    background: #ccc;
}

.wrap {
    margin: 20px;
    padding: 20px;
    padding-right:240px;
    background: #fff;
    overflow:hidden;
}

.main {
    margin: 0 -220px 0 auto;
    width: 100%;
    float:right;
}

.sidebar {
    width: 200px;
    float: left;
    height: 200px;
}

.main, .sidebar {
    background: #eee; min-height: 100px;
}

.clear { clear:both; }
span { background: yellow }

Basically what I've done is change the way your layout is done, so that .main div is floated on the right. To do this, we had to add 2 things:

  1. A padding of 240px on the .wrap div, and
  2. A right margin on the .main div of -220px to properly align the fluid part of the page.

Because we've floated the .main div on the right, the clear: both; now only affects content inside the .main div, as you want.

You can see a demonstration here: http://jsfiddle.net/6d2qF/1/