CSS grid responsive layouts from stacked blocks to 3 columns

I would like to set up a simple CSS grid rule that is responsive to the screen sizes. This can be easily achieved by using CSS @media Rule and CSS grid.

In this example, the CSS grid will have one column for mobile screens, two columns for tablet screens and three columns for larger screens like laptops or desktops.

Let’s mark up the HTML contents first. I will use 6 blocks for the example.

1
2
3
4
5
6
7
8
<div class="grid_items">
  <div class="grid_item">A <br>Lorem ipsum dolor sit amet. <br>Consectetuer adipiscing elit. <br>Cum sociis natoque penatibus et magnis dis parturient montes. <br>nascetur ridiculus mus.</div>
  <div class="grid_item">B</div>
  <div class="grid_item">C  <br>Lorem ipsum dolor sit amet. <br>Consectetuer adipiscing elit.</div>
  <div class="grid_item">D</div>
  <div class="grid_item">E <br>Lorem ipsum dolor sit amet. <br>Consectetuer adipiscing elit. <br>Cum sociis natoque penatibus et magnis dis parturient montes. <br>nascetur ridiculus mus.</div>
  <div class="grid_item">G</div>
</div>

I have created the blocks each with different length of content to showcase more clearly how the grid works.

Now set the CSS rules for the mobile screen view first.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
.grid_items {
  padding: 3.75%;
  display: grid;
  grid-template-columns: 100%;
  grid-column-gap: 0;
  grid-row-gap: 20px;
}
.grid_items &gt; div {
  background-color: RoyalBlue;
  padding: 10px;
}
.grid_items &gt; div:nth-child(3n + 2) {
  background-color: DodgerBlue;
}
.grid_items &gt; div:nth-child(3n) {
  background-color: DeepSkyBlue;
}

The layout should be displayed like below.

CSS grid mobile screen view

We need to change the one column layout to two column layout for the tablet screen sizes by adding CSS @media Rule to the ‘.grid_items’ class.

1
2
3
4
5
6
7
8
9
10
@media only screen and (min-width: 640px) {
  .grid_items {
    grid-template-columns: 47.5% 47.5%;
    grid-column-gap: 5%;
    grid-row-gap: 40px;
  }
  .grid_items &gt; div {
    padding: 20px;
  }
}

Now when the screen width is wider than 640 pixels the layout changes to two columns like below.

CSS grid tablet screen view

Lastly, let’s add little bit more CSS rules to make up the 3 column layout for larger screen sizes.

1
2
3
4
5
6
7
8
9
@media only screen and (min-width: 981px) {
  .grid_items {
    grid-template-columns: 30% 30% 30%;
    grid-row-gap: 50px;
  }
  .grid_items &gt; div {
    padding: 30px;
  }
}

With the added CSS rules the two column layout becomes to three columns like below when the screen size is wider than 981 pixels.

CSS grid desktop screen view

You can also see it in action here at my CodePen page.

See the Pen CSS Grid Responsive – Change of grid layouts by screen size by WebMadeWell (@webmadewell) on CodePen.32161