Subgrids are here! (Almost)

Ananya Neogi - Jun 10 '19 - - Dev Community

Support for subgrid (part of CSS Grid Level 2 specification) has landed on Firefox Nightly! Even though this is not yet getting shipped in any browser, but we can test it in the Nightly version. After trying it out for couple of hours I'm really excited to think about all the possibilities in layouts this will bring, once this gets shipped widely.

To start experimenting with it you’ll need to enable the feature first on Nightly-

  • Go to about:config in the browser
  • Search for subgrid
  • Toggle layout.css.grid-template-subgrid-value.enabled and set subgrid to true.

What are subgrids ?

A grid container that is itself a grid item can defer the definition of its rows and columns to its parent grid container, making it a subgrid. In this case, the grid items of the subgrid participate in sizing the grid of the parent grid container, allowing the contents of both grids to align.

This might sound a little confusing. Let us walk through an example.
Here we have a grid-wrapper inside which we have 3 direct child elements elem1, elem2,elem3.

<div class="grid-wrapper">
  <div class="elem elem1">Element 1</div>
  <div class="elem elem2">Element 2</div>
  <div class="elem elem3">
    <h2>Element 4</h2>
    <p>Element 4 paragraph 1</p>
    <p>Element 4 paragraph 2</p>
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode

Now we position these on grid.

.grid-wrapper {
  display: grid;
  grid-template-columns: 2fr 1fr 4fr;
  gap: 30px;
}

.elem1 {
  grid-column: 1;
  grid-row: 1;
}

.elem2 {
  grid-column: 2 / 4;
  grid-row: 1;
}

.elem3 {
  grid-column: 1 / -1;
  grid-row: 2;
}
Enter fullscreen mode Exit fullscreen mode

We notice that all the immediate children of grid-wrapper are nicely placed on the grid, but not the inner children of .elem3.
What if now we want the p elements to follow the same tracking size as it's parent as well because we don't want to explicitly position them. This is where subgrid comes in.

Replace the exsiting .elem3 with the following and see it in action.

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

In short, subgrid is a new value for the grid-template-columns and grid-template-rows properties. This instructs the grid-template-columns/ grid-template-rowsproperty to use the tracks defined on the parent as the track sizing and number used by the inner grid without explicitly stating.

This is just a basic example. We can create complex and interesting layouts very easily with the combination of grid and subgrid.

References

  1. W3C Spec
  2. MDN docs
  3. Excellent talk by Rachel Andrew at CSSconf EU 2019: Hello Subgrid!
. . . . . . . . . . . . . . . . . . .