Search code examples
cssmenutabsdistributed

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


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!


Solution

  • 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.