Create a Responsive Layout Using Media Queries with CSS Grid

Share this video with your friends

Send Tweet
Published 10 months ago
Updated 9 months ago

Once the browser screen width becomes smaller than a certain size, you can change the layout to fit the screen resolution or browser viewport width. You do this by utilizing media queries (@media) that redefine the values set like grid-template-columns and grid-template-areas.

The grid-template-columns CSS property defines the line names and track sizing functions of the grid columns. While the grid-template-areas CSS property specifies named grid areas, establishing the cells in the grid and assigning them names.

Lesson Challenge

As a challenge, try to write a media query that would change the layout from horizontal to vertical when the screen size is below 700px.

Hint: use @media Queries, grid-template-columns, and grid-template-areas.

Instructor: [0:01] Using the minmax and auto-fit definitely made the layout more responsive for mobile and different browser sizes. However, if you try to load what we have on your phone, you might notice that some parts aren't as responsive as we'd like.

[0:12] We'd like more control over how certain CSS Grid items look depending on the screen size. Here, we have a portfolio layout where I've added in a div with a profile image next to the content div, and they're placed side by side.

[0:25] Before we get started, I'd like to challenge you to create the CSS Grid Layout for yourself before looking at my code. Come back when you're done. I'll be right here waiting. As a hint, remember grid template areas.

[0:35] Welcome back. What we want is for the profile grid and the content grid to be side by side until the screen size reaches a certain size. When that happens, I want it to line up vertically instead.

[0:47] To do this, we set @media (max-width: 700px). When someone's browser gets smaller than 700px, this media query begins to work. We want this media query to to take effect on the container class. When this happens, instead of the layout being two columns, it will become one column with the width of 1fr.

[1:07] The grid-template-area becomes one vertical layout with header, profile, content, and portfolio, in that order. With a wide browser of more than 700px in width, there are two columns for the profile and content section. As the browser gets thinner and we hit 700px, the columns collapse, and the profile and content area are stacked on top of each other.