4

So I have a flex box containing some boxes. All boxes take up one third of the width. Since I used flex-grow my last element wont stick to size of its column. I understand why this is happening but I dont want to use a max-width as a specified width generally isnt great. Any suggestions would be appriciated!

This is what is currently happening: enter image description here

What I want to happen: enter image description here

CODEPEN HERE - https://codepen.io/matt-priestley/pen/ZmXqzr

<ul class="container">
  <li class="boxes"></li>
  <li class="boxes"></li>
  <li class="boxes"></li>
  <li class="boxes"></li>
  <li class="boxes"></li>
  <li class="boxes"></li>
  <li class="boxes"></li>
</ul>
Tobias Wilfert
  • 919
  • 3
  • 14
  • 26
Matt
  • 51
  • 5

3 Answers3

5

Remove flex-grow: 3; from the class .boxes

Here is the updated snippet:

body {
  margin: 0px;
  padding: 0px;
}

.container {
  display: flex;
  flex-wrap: wrap;
  box-sizing: border-box;
}

.boxes {
  background-color: red;
  list-style-type: none;
  height: 200px;
  /*flex-grow: 3;*/
  flex-basis: 33.3%;
  border: 2px solid black;
  box-sizing: border-box;
  min-width: 200px;
}
<ul class="container">
  <li class="boxes"></li>
  <li class="boxes"></li>
  <li class="boxes"></li>
  <li class="boxes"></li>
  <li class="boxes"></li>
  <li class="boxes"></li>
  <li class="boxes"></li>
</ul>
Vikas Jadhav
  • 4,597
  • 2
  • 19
  • 37
1

I went ahead and changed flex-grow to auto, as shown below, and it seems to be working fine. Or you can just remove it entirely, as it is not necessary in this case.

.boxes {
  background-color: red;
  list-style-type: none;
  height: 200px;
  flex-grow: auto;
  flex-basis: 33.3%;
  border: 2px solid black;
  box-sizing: border-box;
  min-width: 200px;
}

P.S. I know you didn't ask for this, but if you want to fix the borders so they don't overlap, you can do this as well:

* {
  box-sizing: border-box;
}

body {
  margin: 0px;
  padding: 0px;
}

.container {
  display: flex;
  flex-wrap: wrap;
}

.boxes {
  background-color: red;
  list-style-type: none;
  height: 200px;
  flex-basis: 33.3%;
  min-width: 200px;
  border-bottom: 2px solid black;
  border-right: 2px solid black;
}

.boxes:nth-of-type(3n+1) {
  border-left: 2px solid black;
}

.boxes:nth-of-type(-n+3) {
  border-top: 2px solid black;
}

Hope this helps!

Gabor Szekely
  • 1,108
  • 5
  • 14
0

use flex-wrap:wrap and set width of each box to 33% - (margin_size)

.container{
  display: flex;
  flex-wrap: wrap;
}

.boxes{
  width: calc(33% - 20px);
  height: 180px;
  background-color: #3C79D1;
  border: 2px solid #003C92;
  margin: 10px;
  box-sizing: border-box;
}

li{
  list-style-type: none;
}
<ul class="container">
  <li class="boxes"></li>
  <li class="boxes"></li>
  <li class="boxes"></li>
  <li class="boxes"></li>
  <li class="boxes"></li>
  <li class="boxes"></li>
  <li class="boxes"></li>
</ul>
Itay Gal
  • 10,706
  • 6
  • 36
  • 75