How to display same number of items for each row with item having minimum size

Viewed 260

I wanted to know if there is a way to always display the same number of items for each rows using grid template. Grid seems the most obvious choice since I want to have items behind aligned horizontally and vertically.

I'm already used to repeat(auto-fill, ...) like this

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(10em, 1fr));
}

But this will only push the minimum number of elements needed to the next line to makes elements on the first line with minimum size of 10em.

What I would like is, considering a list of 6 elements, if the line cannot contain the whole 6 elements with their minimum size, make 2 lines of 3 elements. Again, if there is not enough space, make 3 lines with 2 elements etc.

This could be done with media-query (since I know there will always be 6 elements)

.grid {
  display: grid;
  grid-template-columns: repeat(2, minmax(5em, 1fr));
  gap: 3px;
}

@media screen and (min-width: 20em) {
  .grid {
    grid-template-columns: repeat(3, minmax(5em, 1fr));
  }
}

@media screen and (min-width: 40em) {
  .grid {
    grid-template-columns: repeat(6, minmax(5em, 1fr));
  }
}

.grid > div {
  border: 1px solid black;
  height: 2em;
}
<div class="grid">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
</div>

But this doesn't look very clean, and I would like to know if there is a built-in solution in grid template for this use case (or if there is a solution outside of grid).

0 Answers
Related