Define a Responsive Grid with Media Queries
Now we'll move on to creating a responsive grid layout using media queries.
We'll start with a layout containing 10 boxes and a default number of columns, and then adjust the number of columns based on screen size.
The container has a width of 80% and four 1fr
columns:
#container { wid
Transcript
0:00 Next, let's talk about defining a responsive grid. I have 10 boxes back in my layout, and I've started with a default number of columns. We're repeating four, one fraction columns.
0:12 This is what we see, four columns going across, and my container has a width of 80 percent. It's going to scale down as my screen size scales. Maybe what I want to do is go to a three-column layout, maybe things get too squashed here, and then a two-column layout, and then a one-column layout.
0:30 Well, with what we know so far, we could do this using media queries. If you're familiar with media queries, I could adjust the number of columns, repeat (4, 1fr) columns.
0:41 Then when we get to this size, only repeat three columns, repeat two columns. That is perfectly valid, that's what I'm going to start with. I'm also going to show you another way of creating a responsive grid in just a moment.
0:53 Let's write a basic media query in here. Maybe I'll say up to 1500 pixels wide for the screen. We will select our container, which is this element here with the grid enabled in it. I'll set grid-template-columns to be repeat (3, 1fr) columns.
1:14 We start with four and then we'll hit 1500 and now we get to three columns. Of course, we could adjust this even further. I could duplicate this. Once we hit, I don't know, 600 pixels, I'm just picking numbers. They don't really have any meaning here. We'll then go to a two-column layout. I think that was too late. Maybe 800 pixels.
1:39 We go from four to three and then to two, and then we can go to a single-column layout, maybe at 500 pixels. This is a simple example where all the columns are one fraction, but the concept is the same. You use media queries to adjust the columns or also to adjust the rows if you want.
1:58 Let's go to a single. We don't even need repeat, one fraction here for the column if we're at 500 pixels and below. Here we are, one column to two columns to three columns to four columns. That's just done using media queries, adjusting the columns.
2:17 If you're not familiar with media queries, then maybe this is a bit overwhelming, but they allow us to change certain styles based upon, in this case, the size of the screen, the dimensions of the screen. Next, we'll see another example of creating a responsive grid layout.