问题描述
我使用flexbox来组织页面上的元素。
我想让flexbox使用所有可用的水平空间,所以我添加成长:1
。
然后,我想让同一行上的每个项目具有相同的大小(例如,如果有两个项目,33%如果有三个等等),所以我添加 flex-basis:0
。
在第三步,项目不再包装。如果我改变窗口宽度,每行的项目数总是相同,并且它们的内容被挤压。我不想要。我想要一个项目放在下一行,当他们的宽度变得比它的内容小,因为它的工作在前两个步骤。我试着用 flex-shrink
和其他东西玩,没有成功。
我该怎么办?感谢!
回答TL; DR:添加 min-width:fit-content
工作!
解决方案#2
在较小屏幕上垂直堆叠flex项目的另一种方法是更改: p>
@media screen and(max-width:500px){
ul {flex-direction:column; }
li {flex-basis:auto; }
}
DEMO:
I use flexboxes to organize elements on my page.
I want the flexboxes to use all available horizontal space, so I add flex-grow:1
.
Then I want each item on the same line to be of the same size (e.g. 50% each if there is two items, 33% if there is three, etc), so I add flex-basis:0
.
But at the third step, the items don't wrap anymore. If I change the window width, the number of items per line stays always the same, and their content is squeezed. I don't want that. I want an item to be put on the next line when their width become smaller than it's content, as it works in the first two steps. I tried playing with flex-shrink
and other things, without success.
What can I do ? Thanks !
Answer TL;DR: Adding min-width: fit-content
works !
Although you have flex-wrap
set to wrap
, there is no width
defined for the flex items (li
), and you have flex-basis
set to 0. This means that the initial main size of the flex items is 0. It won't wrap because it can shrink to zero (even if the flex-shrink
property is 0).
Solution #1
One thing you can do is set the flex-basis
property to content
or auto
.
li { flex-basis: auto; }
This tells the flex item to factor in the width of its content.
DEMO: https://jsfiddle.net/s6kgmkn6/3/
This diagram from the flexbox spec tries to explain the difference between flex-basis: 0
and flex-basis: auto
. Personally, I don't find it very clear or helpful. But visit the source page for more details.
Solution #2
Another method to vertically stack flex items on smaller screens is to change the flex-direction
in a media query:
@media screen and ( max-width: 500px ) {
ul { flex-direction: column; }
li { flex-basis: auto; }
}
DEMO: https://jsfiddle.net/s6kgmkn6/4/
这篇关于CSS flexbox(flex-grow / flex-basis) - 相同的宽度,但不包装的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!