3

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).

Franck Bigand
  • 152
  • 2
  • 9
  • 1
    Maybe try https://developer.mozilla.org/en-US/docs/Web/CSS/grid-auto-flow – Zach Jensz May 18 '22 at 10:42
  • @ZachJensz After reading the docs, I'm not exactly sure if this is what I want, but I didn't know about it, so tahnk you anyway. – Franck Bigand May 18 '22 at 12:03
  • 2
    If you always want each row to contain the same amount and also the amount itself & the width is dynamic, you have to use JS. If the amount isn't dynamic, you could consider flex. – Wimanicesir May 18 '22 at 12:26
  • After some search, this question may be a duplicate of https://stackoverflow.com/questions/36494486/keeping-equal-number-of-flex-children-per-line-when-they-wrap – Franck Bigand May 18 '22 at 13:08

0 Answers0