Create a Nested CSS Grid Layout

Share this video with your friends

Social Share Links

Send Tweet

In many cases, you might have a specific area on your website that could benefit from using CSS Grid. Just because your whole page layout is using Grid doesn't mean you can't have a Grid within a Grid.

You'll see how to style a Grid area full of items with more Grid. We'll turn grid on and start applying the usual suspects: grid-template-columns and grid-gap.

You'll see how CSS Grid implicitly adds its style to additional rows without you having to style them. This makes your layout flexible because you don't have to predict how many items are going to be in a Grid area.

Lesson Challenge

When should you let grid implicitly decide what to do vs. explicitly defining it yourself?

Instructor: [0:00] Let's create a portfolio area using nested grid. First things first. We need to first put in the portfolio class and set that to grid area portfolio. Now, we go back up to the container class and add in the new grid area into the grid-template-area. We want the portfolio to come after the content.

[0:18] Let's switch up the grid-template-rows to 1fr for the header, 2fr for the content, 3fr for the portfolio, and then 1fr for the footer. Finally, we need to go back to index.html and add in the new portfolio div to the page. Here we go, we have a portfolio item, and I misspelled portfolio.

[0:38] This section is added. We need to add in grid within the grid that will be each portfolio item. To do this, we'll create a new div with class="portfolio-item" within the portfolio div. Let's multiply this a few times, and here we go.

[0:52] We need to turn on display grid in the portfolio and turn this into a CSS Grid. Because we want this to align horizontally, like we have here, we need to decide how many columns we want in this portfolio. Let's say three columns, all 1fr, to have the same width. Here we go. Now we have grid within the grid. Let's clean it up a little bit with some styling and grid gaps.

[1:15] Let's take a moment to notice something here. We only set three columns at 1fr each, but we have way more than three items in the portfolio.

[1:23] CSS Grid implicitly applies the same styling to the rest of the items if it's more than how many we've explicitly defined. This allows you to create an almost infinite number of grid items without having to worry about counting them and explicitly stating how you want them styled.