blankface
blankface

Reputation: 6347

Restrict css grid row to a specific number of items

* {
  box-sizing: border-box;
}
main {
  padding: 0 20px;
  width: 100%; 
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); 
  grid-gap: 1em;
}

article {
  border-radius: 10px;
  padding: 20px;
  color: #fff;
}

article:nth-child(odd) {
  background-color: #55BBE9;
}

article:nth-child(even) {
  background-color: #afbe29;
}
<main>
  <article>1</article>
  <article>2</article>
  <article>3</article>
  <article>4</article>
  <article>5</article>
  <article>6</article>
  <article>7</article>
  <article>8</article>
  <article>9</article>
</main>

In the above example how can I restrict each row to have only 3 article panes, without setting a max-width? Note that I still want the responsiveness. It's just that when I expand my browser window, I don't want panes 4, 5, 6 etc. to snap up to the first row.

Upvotes: 1

Views: 1766

Answers (1)

MichaelvE
MichaelvE

Reputation: 2578

You just need to set grid-template-columns to auto for each column you want. Screen sizes of 576px or smaller will convert to a single column:

* {
  box-sizing: border-box;
}

main {
  padding: 0 20px;
  width: 100%;
  display: grid;
  grid-template-columns: auto auto auto;
  grid-gap: 1em;
}

@media (max-width: 576px) {
  main {
    grid-template-columns: auto;
  }
}

article {
  border-radius: 10px;
  padding: 20px;
  color: #fff;
}

article:nth-child(odd) {
  background-color: #55BBE9;
}

article:nth-child(even) {
  background-color: #afbe29;
}
<main>
  <article>1</article>
  <article>2</article>
  <article>3</article>
  <article>4</article>
  <article>5</article>
  <article>6</article>
  <article>7</article>
  <article>8</article>
  <article>9</article>
</main>

Upvotes: 1

Related Questions