4

I have a basic two column CSS layout, the CSS looks like

#sidebar {
    width:100px;
}
#main {
    margin-left:100px;
}

And some sample html

<div id="content">
  <div id="sidebar">some sidebar content</div>
  <div id="main">some main content</div>
</div>

This works, but it seems repetitive and error prone that the sidebar width needs to match the main's margin-left value. Is there a better way to do this?

Jeff Storey
  • 56,312
  • 72
  • 233
  • 406

3 Answers3

6

You can use the float property on #sidebar:

#sidebar {
    width:100px;
    float: left;
}

JS Fiddle Example


However, using the above method, if the content of #main causes its height to extend below #sidebar, it will wrap under the sidebar. To avoid this, use the display:table-cell property:

#sidebar, #main {
    display: table-cell;
}

JS Fiddle Example

JSW189
  • 6,267
  • 11
  • 44
  • 72
  • If the main content is longer than the sidebar content and wraps, the wrapping seems to end up under the sidebar... – Jeff Storey Aug 03 '12 at 15:32
  • @JeffStorey. Try adding `display:table-cell` to both `#sidebar` and `#main`: http://jsfiddle.net/HTqHJ/2/ – JSW189 Aug 03 '12 at 15:35
2

CSS

#sidebar { width:100px; float: left; }
#main { float: right; }

HTML

<div id="content">
    <div id="sidebar">my stuff</div>
    <div id="main">some main content</div>
    <div style="clear:both;"></div>
</div>

I recommend 960.gs or BlueprintCSS for basic-html/css styling.

Thomas Schwärzl
  • 9,518
  • 6
  • 43
  • 69
0

You may nest sidebar inside main giving main a padding left and sidebar a -ve margin.

#content{
    width: 100%;
}
#sidebar, #main{
    float: left;
    display: block;
}
#sidebar{
    width: 100px;
    background-color: orange;
    margin-left: -100px;
}
#main{
    padding-left: 100px;
    background-color: green;
    width: 100%;
}

<div id="content">
    <div id="main">
        <div id="sidebar">some sidebar content</div>some main content
    </div>
</div>

Here is the working demo.

Alfred
  • 21,058
  • 61
  • 167
  • 249