Home Blog CV Projects Patterns Notes Book Colophon Search

CSS Layout with Margin

24 Sep, 2013

 

In Simple, Robust Layout with Float, I described how to use display: block and float to layout a site using variable width blocks (so-called fluid layout).

Sometimes you want a fixed width column and a variable width column. One reliable cross-browser way of doing this is to specify a margin on the variable width column that is equal in size to the width of the fixed width column. The variable width column will then float next to the fixed width one.

There are a couple of limitations to this approach, that you don't have with the other one:

With all those caveats, here's some example HTML, similar to before but putting the secondary content first, and having a third level of div for the outer margin:

<div class="secondary">
  <div class="secondary__margin">
    <div class="secondary__content">
      Links:
      <ul>
        <li><a href="">Link 1</a></li>
        <li><a href="">Link 2</a></li>
      </ul>
    </div>
  </div>
</div>
<div class="main">
  <div class="secondary__margin">
    <div class="main__content">
      <h1>Main Content</h1>
      <p>This is all very exciting stuff.</p>
    </div>
  </div>
</div>
.main__content, .secondary__content {
    padding: 10px; 
    /* margin: 10px; */  /* Margin does weird things on floated content, use a separate div as below */
    border: 1px solid #000;
}
.main__margin, .secondary__margin {
    padding: 10px; /* Could use margin here too, but I prefer padding */
}

Now for the layout:

.main {
    margin-left: 150px;
    display: block; /* Otherwise this content will flow around the secondary content. */
}
.secondary {
    width: 150px;
    float: left;
    display: block;
}

Update: Here's a JSFiddle https://jsfiddle.net/xwun547t/2/

Again, note how I keep padding and width on different divs and can still clear blocks using:

.clear {
    height: 0px;
    clear: both;
    display: block;
}

and:

<div class="clear"></div>

Update: With HTML5 and CSS3 you can achieve this using calc(). See http://caniuse.com/#feat=calc

Copyright James Gardner 1996-2020 All Rights Reserved. Admin.