Test HTTP Requests Tools Blog Learn Quizzes Smile API Log In / Sign Up
Test HTTP Requests Tools Blog Learn Quizzes Smile API Log In / Sign Up
« Return to the tutorials list
We have updated the website and our policies to make sure your privacy rights and security are respected.
Click here to learn more about the way our website handles your data.

Remove this message.

Positioning divs side by side with CSS

Daniel Gheorghe Difficulty: 15 / 50 Tweet

This article is old. Be careful! It might contain outdated information.
Here's an alternate resource that I am recommending for this topic.

aligned benches in a park

In this tutorial I will show you the easiest method of positioning HTML divs side by side thus generating a multi-column layout with ease. The only downside for this code is that it doesn't work on IE7, because it doesn't know how to interpret the 'box-sizing' CSS rule.

Speaking of 'box-sizing' this is the rule that solves our grid layout. By default, HTML element widths are calculated by adding width, padding and border. By changing the 'box-sizing' rule to 'border-box', the browser will calculate the width of the object automatically containing it inside whatever is specified for 'width' regardless of padding and border size.

For example, a div that's 100px in width, has a 10px padding and a border of 1px will actually occupy 122px » 100px(width) + 2*10px(left and right padding) + 2*1px(left and right borders). However, if you set the 'box-sizing' property to 'border-box' the div will occupy 100px and the padding and border will be 'inside' the 100px area.

Once you've understood how box-sizing works, just fit your columns inside a container and give them a float property and they should stack naturally one next to the other.

Here's a piece of source code as an example

  
    <style>
      .row { width: 100%; line-height: 50px; overflow:hidden; }
        .column { padding: 10px; text-align: center; float: left; min-height: 50px; background: #eee; border:1px solid #fff; box-sizing:border-box; /*Important!*/ }
        .col2 { width: 20%; } .col4 { width: 40%; }
        .red { background: red; }
        .green { background: green; }
        .blue { background: blue; }
    </style>
    <div class="row">
      <div class="column col4 red">Column 1</div>
      <div class="column col4 green">Column 2</div>
      <div class="column col2 blue">Column 3</div>
    </div>
  
comments powered by Disqus