CSS Grids are a great way of laying out content on the web. But it can be tricky, and needs to be learned.

I am still learning, and here are some of my findings.

align-self and justify-self

An element inside a grid item is automatically stretched to fill the parent elements size in the grid.

This can lead to some weird layouts if the child element is also a grid.

On the child element, you can use align-self for vertical positioning, and justify-self for horizontal positioning. The default value for both CSS properties are stretch.

You could also set this for all children, using align-items or justify-items on the parent element.

The possible values for these properties are:

  • auto
  • normal
  • start
  • end
  • center
  • stretch
  • baseline
  • first baseline
  • last baseline

See Box alignment in CSS Grid Layout | MDN

Different packing algorithms using grid-auto-flow

By default, grid items appear in the same order as in the source document. They are placed using the row value. Which means that items ‘are placed by filling each row in turn, adding new rows as necessary.’

We can change how the browser packs these items by changing the value to one of:

  • row
  • column
  • row dense
  • column dense
  • dense

If source order is not the most important, we can use dense to pack later items higher up in the visual rendering of the grid.

The column value seems to produce a similar layout to dense, but the order of the items is more similar to the source. See grid-auto-flow at MDN for some great interactive examples.

Note (2021-11-26) Firefox has experimental support for the grid-template-rows: masonry and grid-template-columns: masonry properties which will make masonry packing possible natively with CSS only! See https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout/Masonry_Layout