Jeff Storey
Jeff Storey

Reputation: 57212

css 2 column layout

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?

Upvotes: 4

Views: 5218

Answers (3)

JSW189
JSW189

Reputation: 6335

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

Upvotes: 6

Alfred
Alfred

Reputation: 21406

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.

Upvotes: 0

Thomas Schw&#228;rzl
Thomas Schw&#228;rzl

Reputation: 9917

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.

Upvotes: 2

Related Questions