html - Flexbox 没有给元素相等的宽度

标签 html css flexbox

尝试使用最多 5 个元素且最少 3 个元素的 flexbox nav,但它不会在所有元素之间平均分配宽度。

Fiddle

我正在建模的教程是 http://www.sitepoint.com/responsive-fluid-width-variable-item-navigation-css/

SASS

* {
  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>

最佳答案

在您链接的文章中没有提到一个重要的部分,那就是 flex-basis。默认情况下 flex-basisauto

来自 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.)

每个 flex 元素都有一个 flex-basis,它有点像它的初始大小。然后从那里,任何剩余的可用空间按比例分配(基于 flex-grow)在元素之间。对于 auto,该基础是内容大小(或使用 width 等定义的大小)。因此,在您的示例中,文本较大的元素总体上会获得更多空间。

如果你想让你的元素完全均匀,你可以设置flex-basis: 0。这会将 flex 基数设置为 0,然后任何剩余空间(由于所有基数均为 0,因此将是所有空间)将根据 flex-grow 按比例分配。

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

This diagram from the spec很好地说明了这一点。

还有 here is a working example用你的 fiddle 。

关于html - Flexbox 没有给元素相等的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25066214/

相关文章:

html - 如何在动画中途水平翻转图像

html - 使用变换 : origin to center an element

javascript - SVG 动画在调整大小后非常滞后(专家)?

javascript - HTML5 旋转/动画背景

html - 当使用 flexbox 在其包含行中垂直居中列时,如何让 Bootstrap 网格列堆叠在移动屏幕上?

html - 中断在 <p> 标记中不起作用

html - bootstrap中各种col类型有什么区别?

css - 如何使用 z-index 将 svg 放置在其他 svg 之上

css - Flex-box justify-content 在对齐元素时不起作用

css - 防止 flex 元素超过父高度并使滚动条工作