Creating a Simple Mobile First Responsive Layout with CSS Grid

Ole Ersoy
2 min readOct 26, 2023

--

Image by Michael Kleinsasser from Pixabay

Scenario

On mobile screens we want to have two div elements laid out in a column that each have responsive (flexible) widths and are 200px in height. They should be separated by a 20px gap.

On screens with a width greater than 960px we want the div elements laid out in a row having the same 200px height and they should still be separated by a 20px gap. The first div element should take up 40% of the width and the second div should take up 60%.

Approach

We are using CSS Grid because it gives us the an elegant approach to to specifying the gap we want between the elements along with the width specification for medium and larger screens sizes.

This is our markup.

<main class="Grid Grid-lg">
<div class="item-1" style="background-color: yellow;"></div>
<div class="item-2" style="background-color: blue;"></div>
</main>

We will use the following classes to implement the layout. Note that the media query enclosed class Grid-lg must come after the Grid class.

      .Grid {
display: grid;
grid-template-columns: 1fr;
grid-column-gap: 20px;
grid-row-gap: 20px;
grid-auto-rows: 200px;
}
@media (min-width: 960px) {
.Grid-lg {
display: grid;
grid-template-columns: 4fr 6fr;
grid-column-gap: 20px;
grid-auto-rows: 200px;
}
}

Demo

--

--