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

扶醉桌前 提交于 2019-12-18 05:45:29

问题


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!


回答1:


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/




回答2:


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>


来源:https://stackoverflow.com/questions/10551369/how-to-evenly-distribute-menu-items-with-css-when-width-and-quantity-is-not-know

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!