Skip to content

Two-Line Center

Let's say that we want to center one element within its parent, both horizontally and vertically:

A box that is horizontally and vertically centered within its parent

For a long time, this was a notoriously tricky challenge, especially if we wanted to keep the element in-flow.

When Flexbox launched, this challenge became a lot less daunting; we could do it in 3 lines of CSS:

Code Playground

Result

Enable “Tab” for indentation

In CSS Grid, we can use the same trick. For consistency, we'll use align-content instead of align-items (though both should produce a similar result in this circumstance).

Code Playground

Result

Enable “Tab” for indentation

Because we're setting justify-content and align-content to the same value, we can take advantage of a nifty shorthand:

Code Playground

Result

Enable “Tab” for indentation

The place-content property will set both justify-content and align-content at the same time. This means that we now have a CSS centering trick that's just 2 declarations long!

Modern CSS is pretty friggin cool.