问题
Why does the code below not stretch my 100px items?
The results are basically close to this:
[100px|100px|100px|.........]
That looks a lot like flex-start, not flex-stretch. Is this the intended behavior?
I'm looking for:
[...100px...100px...100px...]
.box {
display: flex;
justify-content: stretch;
width: 500px;
}
.item {
width: 100px;
}
<div class="box">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
</div>
回答1:
Because - if you want the items to stretch in width - you have to allow the flex items to grow by adding flex-grow: 1;
:
.box {
display: flex;
justify-content: stretch;
width: 500px;
border: 1px solid red;
}
.item {
width: 100px;
border: 1px solid green;
flex-grow: 1;
}
<div class="box">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
</div>
If you don't mean they should grow, but simply be distributed across the whole width of their container, use justify-content: space-between
od ... space-around
:
.box {
display: flex;
justify-content: space-around;
width: 500px;
border: 1px solid red;
}
.item {
width: 100px;
border: 1px solid green;
}
<div class="box">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
</div>
回答2:
Why doesn't
justify-content: stretch
work?
Because in flexbox there is no such value with justify-content.
So your rule is invalid and the browser defaults to justify-content: flex-start
, the initial setting.
Use the flex-grow
property on flex items to achieve the desired effect.
回答3:
An alternative way to space out items evenly is:
.class {
display: flex;
justify-content: space-between;
}
回答4:
Well, simply put, in order for flex-stretch to kick in, it requires combined item width to be equal or greater than the flex container. In other words, you can use 500px or even something as obscure as 10000px. And it will stretch proportionately. Usually, though... to battle this problem we use 100% on each item. This assumes 100% of the component, but again... if your container is 500px, that's what 100% will equal to. Use that or greater values.
When I was learning flex I found this simple flex generator invaluable, I think it covers the case you're talking about visually.
来源:https://stackoverflow.com/questions/52106717/why-doesnt-justify-content-stretch-work