I have a list of items of variable width inside of a wrappable flex
box.
I want all items to have the same width, so I applied the following CSS attributes: flex-basis: 0
and flex-grow: 1
. With that, each item in every column should have had the same width, independently from its original width.
This was the expected result, which can be achieved by using flex-basis: 30%
.
Unfortunately, this won't work in all cases (if the width of each item is small, there will be a lot of empty space).
Using a fixed width does not solve the issue, because each item can occupy different amounts of space.
This can help illustrate de problem, the "large items" create 5 rows (width of 33% per item) while the "small items" create only 3 rows (width of 20% per item).
I'm also not allowed to use JavaScript.
ul {
display: flex;
flex-wrap: wrap;
}
li {
white-space: nowrap;
flex-basis: 0;
flex-grow: 1;
}
<ul>
<li>Short name</li>
<li>Short name</li>
<li>Short name</li>
<li>Short name</li>
<li>Short name</li>
<li>Short name</li>
<li>Short name</li>
<li>Short name</li>
<li>Long long long name</li>
<li>Short name</li>
<li>Short name</li>
<li>Long long long name</li>
<li>Long long long name</li>
<li>Long long long name</li>
<li>Long long long name</li>
<li>Short name</li>
<li>Short name</li>
<li>Long long long name</li>
<li>Long long long name</li>
<li>Short name</li>
<li>Short name</li>
</ul>
Edit:
I had a misconception about the way flexboxes work. The solution here is to use an appropriate value for flex-basis
.