Something amazing is about to happen to grid layouts. The level 2 specification of CSS grid, called CSS Subgrid, is coming to browsers soon and it's gonna take the already awesome CSS Grid to a whole new level.
Recently, I came across Rachel Andrew's article where she introduced CSS Subgrid and I got super excited and thrilled about the possibilities that come along with CSS Subgrid.
In short — CSS Subgrid makes is possible to construct nested grids within CSS Grid.
Right now (without subgrid) the tracks of the nested grids have no relationship to the tracks on the parent grid. To put it in simple terms — we have a parent container with
display: grid property, therefore its children become grid items. These grid items can also be made the grid containers. But the grid tracks defined for the parent grid container won't be aligned with the grid tracks of the child grid containers since they both are independent of the layout of its content. In some cases, it is necessary for the content and layout of multiple grid items to align with each other.
With CSS Subgrid, a grid container can inherit the definition of its rows and columns from its parent grid container, by making the grid item a subgrid. Subgrid provides the ability to pass the properties of the grid to its nested elements and content-based sizing information back to the parent grid.
These are the two main wins of CSS Subgrid —
- A subgrid can use the grid tracks defined on the parent - for rows, columns or both.
- A subgrid will also inherit the gaps from the parent. The sizing of the items in the subgrid can change the size of the parent tracks.
Here's an example of how nested grid works without subgrid —
But what if we wanted the tracks of nested grid items to be aligned with the tracks of the parent grid?
This is where subgrid comes to the rescue. When we add the property
grid-template-rows: subgrid to the nested grid items, they inherit the row property of the parent grid and align with each other automatically.
This is how it should look if the property is applied.
Note: Currently, there is no browser support for subgrid so I have created an illustration to explain the behavior.
I am eagerly waiting for browsers to support subgrid (hopefully soon) so I can play around with it and figure out interesting use cases.
Feedbacks? Leave a comment :)