2

How can i evenly spread x number of elements in columns. So for example if I have this code

div {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
  grid-gap: 0.5rem;
}

span {
  background: red;
  height: 50px;
}
<div>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
</div>

I want it to fit evenly. So it should never show 3 items on first row, and 1 item on the second row. Instead it should show 2 items on the first and 2 on the second. As long as it can spread it evenly on every row it should do that.

I made a snippet that ALMOST makes it. The problem is when the screen is really small it shows 3 on the first and 1 on the second. Please make note that now I only have 4 items, but it should work dynamically with any number of items.

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
Rane
  • 255
  • 1
  • 6
  • 17
  • 2
    You can use a media query, the `auto-fit` rule will not let you specify a minimum amount of columns; so for smaller screens you could set up a fixed amount of columns – IvanS95 Feb 27 '19 at 20:38

1 Answers1

1

I think a good and easy option is just to be specific on the number of columns for smaller screens; the auto-fit rule will not let you specify a minimum or maximum number of columns and will just adjust them when there is the available space.

div {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
  grid-gap: 0.5rem;
}

span {
  background: red;
  height: 50px;
}

@media (max-width: 500px) {
  div {
    grid-template-columns: repeat(2, minmax(100px, 1fr));
  }
}
<div>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
</div>
IvanS95
  • 5,364
  • 4
  • 24
  • 62
  • The problem has nothing to do with the size of the screen, not really. If I change the 100px to 500px this issue will still happen, but in a different size of the screen. – Rane Feb 27 '19 at 21:02
  • Then the issue needs to be addressed in the layout you expect; if you **know** you can only have 4 columns, then specify that, if not, and you want to fill them automatically, then you need to handle the special cases or limit the size of the column so that stay within your boundaries; Unfortunately it seems that unless you are okay with restricting the layout through JavaScript, you would have to choose 1 approach or the other – IvanS95 Feb 27 '19 at 21:12
  • @Rane this might help you, in this case the user wants a maximum amount of columns, maybe it'll point you in the right direction: https://stackoverflow.com/questions/54907270/how-to-specify-the-maximum-number-of-columns-repeat-will-create-using-auto-fit?noredirect=1#comment96582685_54907270 – IvanS95 Feb 27 '19 at 21:13