DEV Community

Julia Shlykova
Julia Shlykova

Posted on

Subgrid

Introduction

When children of a grid container become grid containers themselves, they don't take track sizing from their parent.

Let's say we want our cards to have two columns with this CSS rule:

grid-template-columns: minmax(5ch, 20ch) 1fr;
Enter fullscreen mode Exit fullscreen mode

Without subgrid

With subgrid

We can see that without subgrid, each card defines its' columns independently, while with subgrid, the parent defines the child's columns.

How to use subgrid

Here is the simple example of using subgrid:

Let's start with defining html structure:

<div class="grid">
    <div class="subgrid">
        <div class="grandchild"></div>
    </div>
</div>
Enter fullscreen mode Exit fullscreen mode

We have to set display: grid for the main container and its' child:

.grid {
    display: grid;
}

.subgrid {
    display: grid;
}
Enter fullscreen mode Exit fullscreen mode

And now it's time to define track sizing:

.grid {
    grid-template-columns: repeat(8, 1fr);
}

.subgrid {
    grid-column: 2 / -1;
    grid-template-columns: subgrid;
}
Enter fullscreen mode Exit fullscreen mode

Here, track sizing of the child is inherited from the parent by setting its' own grid-template-columns to subgrid.

So, how to position the grandchild so it will occupy the cell in the third column of the grandparent?

.grandchild {
    grid-column: 2 / 3;
}
Enter fullscreen mode Exit fullscreen mode

Since the child has its' own count, the second column of the child will be the third one of the parent.

Top comments (0)