Divide Width of Element Between Child Divs With CSS

Viewed 21228

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.

4 Answers

I'd like to expound on @lingeshram's answer. Flexboxes have come so far that I think it's really the way to do it now. If you have to support old browsers, be sure to check caniuse first.

.container {
  display: flex; /* or inline-flex */
}

.col {
  flex-grow: 1;
  border: 1px solid #000;
}

.col2x {
  flex-grow: 2;
  border: 1px solid #000;
}
Evenly split three children
<div class='container'>
  <span class='col'>Inner 1</span>
  <span class='col'>Inner 2</span>
  <span class='col'>Inner 3</span>
</div>

<br>
Evenly split two children
<div class='container'>
  <span class='col'>Inner 1</span>
  <span class='col'>Inner 2</span>
</div>

<br>
Split three children, but the middle is twice the size of the others
<div class='container'>
  <span class='col'>Inner 1</span>
  <span class='col2x'>Inner 2</span>
  <span class='col'>Inner 3</span>
</div>

Here is a pretty good guide to the different ways you can use flexbox.

Related