Divide Width of Element Between Child Divs With CSS

Gary picture Gary · Jul 8, 2011 · Viewed 17.5k times · Source

I have a varying number of inline-block divs that I want to collectively take up 100% of their parent. Can this be done without JavaScript? The only way I can think of is with a table but it's of course bad practice to use a table solely for layout purposes.

|----------------------|
|{  div 1  }{  div 2  }|
           or
|{div 1}{div  2}{div 3}|
|----------------------|

I have also tried { display:block; float:left; } but it doesn't seem to make a difference.

Answer

Ben Hull picture Ben Hull · Jul 8, 2011

You can use display:table-cell on your inner divs to do this. For the browser to make the inner divs behave like table cells, it also needs two layers of containing elements: one to acts as the table, and another to act as the table-row.

For a structure like this:

   <div class="outer">
       <div class="middle">
          <div class="inner">Item 1</div> 
          <div class="inner">Item 2</div> 
          <div class="inner">Item 3</div> 
          <div class="inner">Item 4</div> 
       </div>
   </div>

Use this CSS:

div.outer {display:table;}
div.middle {display:table-row;}
div.inner {display:table-cell;}

A nice structure to use is a UL wrapped in a DIV: the DIV acts as a table, the UL as a row, and the LI's as table-cells.

This technique is not well supported in older browsers - for anything older than IE8, you're out of luck entirely.

Let me know if you need more sample code than that!