如何使flexbox项目大小相同?

时间:2021-06-19 14:04:59

I want to use flexbox that has some number of items that are all the same width. I've noticed that flexbox distributes the space around evenly, rather than the space itself.

我想使用具有一些宽度相同的项目的flexbox。我注意到flexbox会均匀地分布空间,而不是空间本身。

For example:

例如:

.header {
  display: flex;
}

.item {
  flex-grow: 1;
  text-align: center;
  border: 1px solid black;
}
<div class="header">
  <div class="item">asdfasdfasdfasdfasdfasdf</div>
  <div class="item">z</div>
</div>

The first item is a lot bigger than the second. If I have 3 items, 4 items, or n items, I want them all to appear on the same line with an equal amount of space per item.

第一项比第二项大很多。如果我有3个项目,4个项目或n个项目,我希望它们全部显示在同一行上,每个项目的空间量相等。

Any ideas?

有任何想法吗?

http://codepen.io/anon/pen/gbJBqM

http://codepen.io/anon/pen/gbJBqM

3 个解决方案

#1


68  

Set them so that their flex-basis is 0 (so all elements have the same starting point), and allow them to grow:

设置它们以使它们的flex-basis为0(因此所有元素具有相同的起点),并允许它们增长:

flex: 1 1 0

flex:1 1 0

#2


21  

You could add flex-basis: 100% to achieve this.

您可以添加flex-basis:100%来实现此目的。

Updated Example

更新的示例

.header {
  display: flex;
}

.item {
  flex-basis: 100%;
  text-align: center;
  border: 1px solid black;
}

For what it's worth, you could also use flex: 1 for the same results as well.

对于它的价值,您也可以使用flex:1获得相同的结果。

The shorthand of flex: 1 is the same as flex: 1 1 0, which is equivalent to:

flex的简写:1与flex相同:1 1 0,相当于:

.item {
  flex-grow: 1;
  flex-shrink: 1;
  flex-basis: 0;
  text-align: center;
  border: 1px solid black;
}

#3


3  

Adding width: 0 helped me solve the problem

添加宽度:0帮我解决了这个问题

    .item {
      flex-grow: 1 1 0;
      width: 0;
    }

here is the link that help me solve my problem: Always equal flexbox columns

这是帮助我解决问题的链接:始终等于flexbox列

#1


68  

Set them so that their flex-basis is 0 (so all elements have the same starting point), and allow them to grow:

设置它们以使它们的flex-basis为0(因此所有元素具有相同的起点),并允许它们增长:

flex: 1 1 0

flex:1 1 0

#2


21  

You could add flex-basis: 100% to achieve this.

您可以添加flex-basis:100%来实现此目的。

Updated Example

更新的示例

.header {
  display: flex;
}

.item {
  flex-basis: 100%;
  text-align: center;
  border: 1px solid black;
}

For what it's worth, you could also use flex: 1 for the same results as well.

对于它的价值,您也可以使用flex:1获得相同的结果。

The shorthand of flex: 1 is the same as flex: 1 1 0, which is equivalent to:

flex的简写:1与flex相同:1 1 0,相当于:

.item {
  flex-grow: 1;
  flex-shrink: 1;
  flex-basis: 0;
  text-align: center;
  border: 1px solid black;
}

#3


3  

Adding width: 0 helped me solve the problem

添加宽度:0帮我解决了这个问题

    .item {
      flex-grow: 1 1 0;
      width: 0;
    }

here is the link that help me solve my problem: Always equal flexbox columns

这是帮助我解决问题的链接:始终等于flexbox列