BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage News CSS Grid Level 2 Preview: Adding Subgrid Support for Layout Inheritance

CSS Grid Level 2 Preview: Adding Subgrid Support for Layout Inheritance

This item in japanese

CSS Grid is a relatively new feature in CSS which defines a two-dimensional grid-based layout system, optimized for user interface design. It was designed to replace existing third party grid systems such as 960 which rely on a complex set of classes. During the initial release of CSS Grid, several features were not ready; as a result, CSS Grid was marked as a 'level 1' module, leaving the option to add additional capabilities in future releases.

Two years later, CSS Grid level 2 is almost ready to be released. It's a smaller update that focuses on the release of a new functionality called subgrid, which is available for testing in Firefox nightly.

Subgrid is a new property that allows developers to align the dimensions of a child element with the size definition of its parent. It is used inside grid-template-columns and grid-template-rows. Instead of directly defining the track sizing of our grid, we can inherit the track sizing used by our direct parent.

For example, instead of defining the following grid-template-rows:

grid-template-rows: 150px 200px 150px;

We can instruct the inner grid to inherit the values from its direct parent by using subgrid:

grid-template-columns: subgrid;

Subgrid is an advanced feature that tackles specific limitations in the current CSS Grid implementation that makes it challenging to line nested grid items up with the primary grid. Sites that do not use nested grids will not be affected by this change.

A common use case for subgrid is enforcing similar size tracking across columns/rows multiple child elements. For example, creating a list of widgets with a header and content will result in an uneven height of the header/content as shown in the example below. This is happening as each element of the child grid determines its own row height, making it difficult to enable the rows to expand while preserving a unified height.

Before the release of subgrid, solving this and similar problems became very difficult, but subgrid was created to solve these exact scenarios, making the process quite simple.

Using the example above of a two-row widget layout, a correct CSS will look something like this:

.grid {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    gap: 20px;
}

.widget {
    display: grid;
    grid-template-rows: subgrid;
    grid-row: auto / span 2;
    gap: 0px;
}

.header {
    font-weight: bold;
}

.content {
    text-align: justify;
}

While there is no exact release date yet, you can play with subgrid using Firefox Nightly.

To find out more about subgrid, head to MDN Web Docs for a complete list of features with examples.

Rate this Article

Adoption
Style

BT