Flexbox没有给元素相等的宽度

html CSS

泡芙

2020-03-22

尝试一个最多包含5个项目且只有3个项目的flexbox导航,但是它没有在所有元素之间平均分配宽度。

小提琴

我为此建模的教程是http://www.sitepoint.com/response-fluid-width-variable-item-navigation-css/

萨斯

* {
  font-size: 16px;
}

.tabs {
  max-width: 1010px;
  width: 100%;
  height: 5rem;
  border-bottom: solid 1px grey;
  margin: 0 0 0 6.5rem;
  display: table;
  table-layout: fixed;
}
.tabs ul {
  margin: 0;
  display: flex;
  flex-direction: row;
}
.tabs ul li {
  flex-grow: 1;
  list-style: none;
  text-align: center;
  font-size: 1.313rem;
  background: blue;
  color: white;
  height: inherit;
  left: auto;
  vertical-align: top;
  text-align: left;
  padding: 20px 20px 20px 70px;
  border-top-left-radius: 20px;
  border: solid 1px blue;
  cursor: pointer;
}
.tabs ul li.active {
  background: white;
  color: blue;
}
.tabs ul li:before {
  content: "";
}
<div class="tabs">
  <ul>
    <li class="active" data-tab="1">Pizza</li>
    <li data-tab="2">Chicken Noodle Soup</li>
    <li data-tab="3">Peanut Butter</li>
    <li data-tab="4">Fish</li>
  </ul>
</div>

第2565篇《Flexbox没有给元素相等的宽度》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
伽罗 2020.03.22

There is an important bit that is not mentioned in the article to which you linked and that is flex-basis. By default flex-basis is auto.

From the spec:

If the specified flex-basis is auto, the used flex basis is the value of the flex item’s main size property. (This can itself be the keyword auto, which sizes the flex item based on its contents.)

Each flex item has a flex-basis which is sort of like its initial size. Then from there, any remaining free space is distributed proportionally (based on flex-grow) among the items. With auto, that basis is the contents size (or defined size with width, etc.). As a result, items with bigger text within are being given more space overall in your example.

If you want your elements to be completely even, you can set flex-basis: 0. This will set the flex basis to 0 and then any remaining space (which will be all space since all basises are 0) will be proportionally distributed based on flex-grow.

li {
    flex-grow: 1;
    flex-basis: 0;
    /* ... */
}

This diagram from the spec does a pretty good job of illustrating the point.

And here is a working example with your fiddle.

西里Near 2020.03.22

要使用创建宽度相等的元素Flex,您应该将其设置为子元素(弹性元素):

flex-basis: 25%;
flex-grow: 0;

它将赋予行中所有元素25%的宽度。他们不会成长并一一走下去。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android