3

I am having a small problem. I was always using floating to arrange my elements. I am moving to flexbox, I made some examples and everything was good but I am making an example which things are not going well.

I have a container having between 1 to 12 products, 4 for each line. I made a simple example using only four and it is working, but now I am making an example with five elements, the first row looks fine, but the fifth element take 100% of the products container, but I want it to take only 25%, the sixth takes 25% and so on.

That what I see:

enter image description here

Here is my code :

<div class="container-2">
      <div class="item-2">
        ...
      </div>
      <div class="item-2 p2-2">
        ...
      </div>
      <div class="item-2">
        ...
      </div>
      <div class="item-2 pp2">
        ...
      </div>
      <div class="item-2 pp2">
        ...
      </div>
</div>

And That is my CSS :

.container-2 {
  max-width: 1200px;
  margin: 0 auto;

  padding: 20px 15px;
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
}

.item-2 {
  padding: 0 15px;
  flex: 1 0 25%;
  margin-bottom: 40px;
}
Michael Benjamin
  • 307,417
  • 93
  • 525
  • 644
TaouBen
  • 1,091
  • 12
  • 28

5 Answers5

3

You have the items set to flex: 1 0 25%.

This breaks down to:

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

Remove flex-grow: 1. It's telling the items to consume free space.

Try this: flex: 0 0 25%

For more details and other options, see these posts:

Michael Benjamin
  • 307,417
  • 93
  • 525
  • 644
1

I recommend to use flex: 0 1 auto.

TMOTTM
  • 2,984
  • 5
  • 26
  • 48
1

I would use box-sizing: border-box; and flex: 0 1 25%; for .item-2

Roman
  • 884
  • 1
  • 9
  • 19
1

Make it correct -

.item-2 {
      padding: 0 15px;
      flex: 0 0 25%;
      margin-bottom: 40px;
    }
0

Also, you have to properly set up the box-sizing attribute:

*, *:before, *:after {
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}

Without this, in some situations, your 4th element will be falling to the next row