Skip to content

Prima​Materia's

CSS Subgrids

Here are a few examples of CSS subgrid usage that I find very useful: subgrid with a custom gap, and auto-fitted and auto-filled subgrids set in minmaxed columns and automatically wrapping the rows.

§ Simple example

Subgrids are grids in which cells are placed within the cells of the parent grid. This allows for alignment across separate components.

See the Pen subgrid-simple-example by Matus Benko (@PrimaMateria) on CodePen.

The parent grid is 3x3. Three items are placed in each column, with each item spanning three rows. Subitems, which are the child divs of the items, are placed in the cells of the parent grid and are aligned across the boundaries of their container items.

§ Subgrid gap

Subgrids can have their own gap.

See the Pen subgrid-simple-example by Matus Benko (@PrimaMateria) on CodePen.

The parent grid has a 16px gap. The item has a reduced gap of 4px. The first and second items were joined to demonstrate that both the parent grid's gaps - between columns and between rows - are overridden.

Each subgrid can have a different gap, although in the end, the cells look oddly misaligned.

§ Subgrid auto-fit

This is very useful for rendering dynamic count of items.

See the Pen subgrid-autofit by Matus Benko (@PrimaMateria) on CodePen.

The parent grid's column width is calculated to be at least 100px or 1 fraction of the available space. When the first item is added, the column expands to 1fr. If the number of items increases and would cause the column to resize to less than the minimum 100px, the item will instead be placed in the next available row - in this case, row 4, as the first 3 rows are already spanned by items.

I must confess that before I realized subgrid items can be dynamically wrapped to multiple rows and don't always need to be placed in a predefined parent grid cell, I used a lot of JavaScript code to measure available space and calculate the number of columns, as well as the exact row and column number for each item. Whoops.

§ Subgrid auto-fill

Auto-fill works the same way as auto-fit works. I am including this example just for a nice visualization of the difference between these two.

See the Pen subgrid-autofit by Matus Benko (@PrimaMateria) on CodePen.

When using auto-fill, the grid will also include empty columns. This ensures that the column size remains consistent from the beginning, just like in a fully filled row.

Reddit comments

See on Reddit

GitHub comments