Sticky Grids

We can use a combination of `display: grid` and `position: sticky` in order to create sticky columns and rows.

This effect can be seen in most spreadsheet applications, when a row or column of data can be "pinned" in place. This allows a user to scan tabular data while holding the row or column in place as a reference. To understand how to achieve this, we will build sticky columns, then sticky rows, then put the two together into a full table.

To get started, let's declare some utility classes to create grid layouts

Sticky Column

First we create a 1xN grid of cells and apply a sticky position to the cell (column) we wish to pin.

sticky
1
2
3
4
5

Multiple Sticky Rows

We can orient our grid along another dimension as well and apply a sticky positon relative to the vertical instead of horizontal.

sticky
1
2 - sticky
3
4
5

Sticky Cells

Putting the above together, our strategy with a NxM grid is to render out the cells, then apply the correct sticky class to each cell, based on whether it falls within a sticky column or sticky row. We must also set the z index for these cells to ensure the pinned data is never covered.

(1,1)
(1,2)
(1,3)
(1,4)
(1,5)
(1,6)
(2,1)
(2,2)
(2,3)
(2,4)
(2,5)
(2,6)
(3,1)
(3,2)
(3,3)
(3,4)
(3,5)
(3,6)
(4,1)
(2,2)
(4,3)
(4,4)
(4,5)
(4,6)
(5,1)
(5,2)
(5,3)
(5,4)
(5,5)
(5,6)
(6,1)
(6,2)
(6,3)
(6,4)
(6,5)
(6,6)

References

For a great primer on css grid, checkout the guide from css-tricks