Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How evenly space divs (each of a different width) within a parent div?

I have seen this solution for evenly spacing DIVs: (Fluid width with equally spaced DIVs) but it requires that the DIVs are all of the same width. This will not work in my case. I have 5 DIVs that are all of different widths and would like to space them evenly. Is this possible without javascript?

For example:

<!-- The text should not wrap, but be on one line for each div -->
<div class="item" id="item1">Item One</div>
<div class="item" id="item2">Item # Two</div>
<div class="item" id="item3">Item Three</div>
<div class="item" id="item4">Item Four</div>
<div class="item" id="item5">Item Five, the Last</div>

I need it to work in IE8+, Firefox 4+, Chrome, Safari.

EDIT: One other requirement: the divs should have no space to the right of the last DIV or left of the first DIV. So the whitespace between them is equal to the difference between the sum of their widths and the width of the container div.

like image 368
Don Rhummy Avatar asked Feb 06 '14 18:02

Don Rhummy


1 Answers

you could use : display:flex; on a parent container

.evenly {
  display:flex;
  justify-content:space-between;
  border:solid;
}
.evenly div {
  white-space:nowrap;
  background:gray;
}
<div class="evenly">
  <div class="item" id="item1">Item One</div>
<div class="item" id="item2">Item # Two</div>
<div class="item" id="item3">Item Three</div>
<div class="item" id="item4">Item Four</div>
<div class="item" id="item5">Item Five, the Last</div>
</div>

DEMO: http://codepen.io/anon/pen/wxtqJ

extra border and background for demo purpose.

If you need an alternative that works for older nav, you can use text-align:justify properties: http://codepen.io/anon/pen/FnDqr .

like image 171
G-Cyrillus Avatar answered Nov 15 '22 19:11

G-Cyrillus