Why doesn't justify-content: stretch work?

Viewed 19956

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>

5 Answers

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>

Why doesn't justify-content: stretch work?

Because in flexbox there is no such value with justify-content.

See MDN: stretch is not supported by flexible boxes (flexbox).

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.

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.

Yes, it is supposed to look like that for flex containers, flex-start is used instead of flex-stretch. Here is what W3C states about justify-content:stretch

The justify-content property applies along the main axis, but since stretching in the main axis is controlled by flex, stretch behaves as flex-start.

Also, I might be late in answering the question but MDN has also updated their page about justify-content. See the notes under stretch property MDN

An alternative way to space out items evenly is:

.class {
    display: flex;
    justify-content: space-between;
}
Related