Tushar Tushar - 3 months ago 11
CSS Question

strictly distribute width equally and dynamically via flex box

How does one enforce equal distribution of width irrespective of the content size inside of it using a flex box?

I have

ul
element which contains three
li
elements that have to be of equal width. Using
flex: 1 0 0
doesn't work correctly as you can see in the demo. The third
li
element takes up all the space.

UPDATE
The list is dynamically created and using Javascript to calculate percentages is not what I am looking for.



ul {
list-style: none;
display: flex;
flex-direction: row;
width: 100%;
background-color: #F00;
padding: 2px;
margin: 0;
box-sizing: border-box;
}

li {
background-color: #eee;
border: 1px solid #000;
flex: 1 0 0;
}

<ul>
<li>AAAAAAA</li>
<li>BBB</li>
<li>CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC</li>
</ul>




Answer

Flexbox can't do that but there is another option.

CSS Tables

Of course, if the text is too long it will overflow, we can fix that with word-break:break-all.

ul {
  list-style: none;
  display: table;
  width: 100%;
  background-color: #F00;
  padding: 2px;
  margin: 0;
  margin-bottom: 10px;
  box-sizing: border-box;
  table-layout: fixed;
}
li {
  display: table-cell;
  background-color: #eee;
  border: 1px solid #000;
  word-break: break-all;
}
<ul>
  <li>AAAAAAA</li>
  <li>BBB</li>
  <li>CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC</li>
</ul>


<ul>
  <li>AAAAAAA</li>
  <li>BBB</li>
  <li>CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC</li>
  <li>DDDDDDDDDDDDDDDDDD</li>
</ul>