Nested Grids with subgrid in CSS

Applying display: grid to an element creates a grid formatting context, and turns its immediate child elements into grid items. Children of grid items, however, don’t participate in the grid formatting context. Instead, they behave according to the rules of normal flow, as pictured below.

As the image above illustrates, neither child of Item 1 participates in the grid formatting context of its “grandparent” element. By specifying a subgrid, however, we can force our grandchild elements to line up with the grid tracks established by the grandparent element.

First, let’s look at the markup for the layout shown in the image above:

<div class=”grid”>

<div class=”grid-item-1″>

Item 1

<div class=”subgrid-item”>Child of Item 1</div>

<div class=”subgrid-item”>Child of Item 1</div>

</div>

<div class=”grid-item-2″>Item 2</div>

<div class=”grid-item-3″>Item 3</div>

<div class=”grid-item-4″>Item 4</div>

</div>

The markup is straightforward. Our grid container has four child elements, and its first child has two children of its own.

Here’s the CSS. I’ve removed non-essential declarations such as background colors:

.grid {

gap: 2rem;

display: grid;

grid-template-columns: repeat(12, 1fr);

grid-template-rows: repeat(2, 1fr);

}

/*Spans 10 columns */

.grid-item-1 {

grid-column: 1 / 11;

}

/* Spans two columns */

.grid-item-2 {

grid-column: 11 / 13;

}

/* Spans six columns each */

.grid-item-3 {

grid-column: 1 / 7;

}

.grid-item-4 {

grid-column: 7 / 13;

}

.subgrid-item {

font-size: .5em;

padding: .5rem;

}

We haven’t yet defined a subgrid for this layout. Adding a subgrid requires adding two declarations to a grid item:

  • display: grid (or display: inherit ), which creates a grid formatting context for children of the grid item
  • grid-tempiate-coLumns: subgrid or grid-template-rows: subgrid

Let’s add a column subgrid for .grid-item-1 . We’ll also make each child element take up five columns:

.grid-item-1 {

grid-column: 1 / 11;

/* Adopts the adopts the parent’s grid tracks */

display: grid;

grid-template-columns: subgrid;

}

.subgrid-item:first-child {

grid-column: 1 / 6;

}

.subgrid-item:last-child {

grid-column: 6 / 11;

}

Elements within the subgrid align with the grid tracks of the parent grid container, as pictured below.

The child elements of Item 1 now align with the grid tracks of div.grid , minus any padding applied to .grid-item-1 .

You may also have noticed from the screenshots that the Item 1 text wraps in our subgrid. Although that text isn’t an element, it participates in the grid formatting context of its parent. As a result, its width is constrained to the width of a single grid track.

Unfortunately, Firefox (versions 71 and above) is the only browser that currently supports subgrid.

Source: Brown Tiffany B (2021), CSS , SitePoint; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *