I've read a lot on evenly distributing elements using css but every solution i've found requires you to know and define the width and/or the number of elements being distributed.
I have a container that is of a fixed width - within here could be any number of li elements of an automatic width which need to be distributed evenly across the parent element from left to right.
Here is my markup - except there could be any number of tabs with any length text in them.
<ul class="tabs">
<li class="tab active" id="tab-1"><span class="tab-title">Tab 1</span></li>
<li class="tab " id="tab-2"><span class="tab-title">Tab 2</span></li>
<li class="tab " id="tab-3"><span class="tab-title">Tab 3</span></li>
<li class="tab " id="tab-4"><span class="tab-title">Tab 4</span></li>
</ul>
So Even Distribution with css when the number of elements and width is dynamic - can it be done?
Seems like such an obvious thing to want to do - Damn CSS!
The "space-evenly" value for the justify-content property distributes the space between items evenly. It is similar to space-around but provides equal instead of half-sized space on the edges. Can be used in both CSS flexbox & grid.
For this, you can use the CSS display:table-cell
property. Write this:
.tabs {
display: table;
width: 300px;
border: 1px solid green;
}
.tabs li {
display: table-cell;
border: 1px solid red;
height: 40px;
}
Check this JSFiddle.
Here is a solution that keeps even widths when contents overflow the allocated cell width, using flexbox:
ul.tabs {
display: flex;
flex-wrap: nowrap;
align-items: stretch;
list-style-type: none;
margin: 0;
padding: 0;
}
ul.tabs>li.tab {
flex: 1;
text-align: center;
/* just adding visibility to the tabs */
border: 1px solid rgba(0,0,0,.12);
padding: 10px;
}
<ul class="tabs">
<li class="tab active" id="tab-1"><span class="tab-title">Tab 1</span></li>
<li class="tab " id="tab-2"><span class="tab-title">Tab 2</span></li>
<li class="tab " id="tab-3"><span class="tab-title">Tab 3. This is a very long tab and should overflow...</span></li>
<li class="tab " id="tab-4"><span class="tab-title">Tab 4</span></li>
</ul>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With