Create a Grid Layout of List Items Using CSS Grid Templates

Colby Fayock
InstructorColby Fayock

Share this video with your friends

Send Tweet
Published 2 years ago
Updated a year ago

In this lesson, we'll walk through turning a list of Pokemon into a grid using CSS Grid. We'll start by using the grid display property, setting up static and dynamic columns, and using the gap feature to configure spacing in our grid.

Colby Fayock: [0:00] We're going to start off with the Gatsby app where we have a list of our Pokémon. In our code, we're using this hook usePokemon, which allows us to grab all of our Pokemon and map it out into a list.

[0:08] We're able to see all of our Pokémon if we scroll through this list, but what if we want it to display in a grid so we could see more from a higher level? To do this, we can use CSS Grid Layout. With a few lines of CSS, it allows us to create a grid of all of our items.

[0:21] To get started, the first thing we want to do is add display: grid; to our Pokédex. If we refresh the page, you'll notice that it hasn't done anything yet. We still need to define the columns that we want.

[0:29] To do that, we want to define our grid-template-columns, and to test that out, we can define three columns with 10em. If we reload the page, now we can see that it's starting to actually look like a grid, but what if we wanted each of those columns to take up the full row?

[0:41] To start, we can change these 10em to 1fr. Now we can see all those columns expand to its container, but this gives us a lot of whitespace, and it seems like we can fit another one up there. What we can do is also use a function called repeat(). We can tell repeat() that we wanted to auto-fit, and we can also reduce the 1frs to just 1fr.

[0:57] At that point, it looks like we're back to square one where it's just in the list, but the issue is we're trying to define each column as 1fr. To fix this, we can use a function called minmax() where we can specify a minimum size of 10em and leave that 1fr as the max.

[1:10] Now we can see all the columns take up all the space but with a standard size.Since we're defining it as the min max, we can also see that it's responsive and collapses down as it gets smaller.

[1:19] Finally, what if these appear a little bit too tight, and we want to add a little white space? We can make use of the grid-gap property and set the spacing to 1em. As you can see, we still have our grid, but we have a little bit of extra white space between the columns.

[1:30] In review, we had a list of Pokémon, but we wanted to show it in a grid. To do that, we set the display to grid. We also set up the grid-template-columns to repeat through each item and make it auto-fit with a minimum and maximum of 10em and 1fr.

[1:42] Finally, to give a little extra white space we added a grid-gap of 1em. With that, we now have our grid of Pokémon.