Vertically Centering Divs with CSS Grid


Every dev knows how irritating it is the first time you try to vertically center a div. It's one of those things that seems a lot more complicated than it should be, and it is... Kind of. The truth is there are just so many different scenarios, with so many implementations that it makes it a bit tedious when looking for one concrete answer.

However CSS Grid Layout (CSS Grid) provides an extremely simple solution. If you're unfamiliar, CSS Grid is a 2d layout system broken down into an x(rows) and y(columns) axis layout. Hence why it's called a grid. If the parent container is a grid, you can then align the child elements along either axis as desired. To do this from the parent we need to add two properties:

  • align-items: Aligns the child elements along the columns (y) axis.
  • justify-items: Aligns the child elements along the rows (x) axis.

You can see a working example of this application below:

See the Pen GdRQGK by My Weekend Project (@MWP) on CodePen.

Easy right? CSS Grid can do a lot more though! Be sure to check it out if you haven't already.