1

* {
  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.

3
  • I'd suggest use Bootstrap's grid, rather than trying to write your own. Commented Oct 12, 2018 at 0:42
  • 1
    @DanielWilliams sometimes you don't want/need Bootstrap, similar to not wanting jQuery all the time. Not that your suggestion is completely invalid, mind :) Commented Oct 12, 2018 at 0:44
  • and why you cannot set max-width? it seems a good solution Commented Oct 12, 2018 at 0:45

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

4 Comments

Would you then use media queries for 1-col mobile layout?
That's exactly what I would do: grid-template-columns auto; A single auto will tell the browser to just use 1 column.
I am not sure how this answer the question, where is the responsive part here and the 300px as max value?
Ok, I've included a media query for 576px. 300px is too small to demo on this site.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.