0

I've got a container with items that are set to flex:1 0 25%; which take up roughly one third each, so I have rows of 3. When it comes to the last row where there are only two items, they go 50% width each, why is that?

.gallery {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
}
.item {
    flex: 1 0 25%;
}
Georgi Hristozov
  • 3,899
  • 2
  • 17
  • 23
Elliott Coe
  • 543
  • 3
  • 6
  • 18

1 Answers1

2

As already mentioned in the comments, the behavior you described is because you set the flex property of your flex items to:

flex: 1 0 25%;

which is short for:

flex-grow: 1;
flex-shrink: 0;
flex-basis: 25%;

This means, that all of your flex-items have a width basis of 25% of the flex-container, while they cannot be smaller (no-shrink) and instead take all of the remaining space because of flex-grow: 1;

And because of that your flex-items will behave as follows:

1 flex-item will take 100% of the flex-containers width,

2 flex-items will each take 50% of the flex-containers width,

3 flex-items will each take 33.3333% of the flex-containers witdh and so on.

This also happens to apply for each row when you have flex-wrap: wrap;

If you want each row to have 3 items with a width of roughly 1/3, I suggest you try to set the flex property of your flex items to:

flex: 0 0 33.3333%

CodePen: https://codepen.io/anon/pen/jeXMBK?editors=1100#0

Alternatively you could use CSS-Grid which is the better choice most of the time, if you are dealing with 2-dimensional layouts.

Edit: Added CodePen sample

M. Barzel
  • 36
  • 3