How to evenly distribute menu items with CSS when width and quantity is not known?

Ralphonz picture Ralphonz · May 11, 2012 · Viewed 11.4k times · Source

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!

Answer

sandeep picture sandeep · May 11, 2012

For this your can css display:table-cell property. Write like this:

.tabs{
    display:table;
    width:300px;
    border:1px solid green;
}
.tabs li{
    display:table-cell;
    border:1px solid red;
    height:40px;
}

Check this http://jsfiddle.net/px7Uf/