Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto spread evenly columns with css grid

Tags:

css

css-grid

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.

like image 345
Rane Avatar asked Oct 21 '25 05:10

Rane


1 Answers

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>
like image 98
IvanS95 Avatar answered Oct 23 '25 11:10

IvanS95