Two simple methods to vertically and horizontally center content with CSS


Centering with CSS—especially vertically, used to be a bit of an in-joke, back in the old days. I emphasise old days because vertical centering hasn't been an issue since Flexbox gained majority support, 7 years ago!

I primarily use Flexbox for vertical centering, but Grid can also be useful. In this post, we’re going to use both to create a little utility class.

The .center-xy utility permalink

Using CSS Grid, we can achieve horizontal and vertical centering with 4 lines of CSS:

Code language
.center-xy {
  display: grid;
  place-items: center;

The place-items property is a shorthand for justify-items and align-items, so because we’ve effectively set both to center, the direct descendants of .center-xy will be centered. Neat, right?

I said descendants for a reason. This will place all descendants in the center, so things get pretty wild when you have more than one descendant. That’s where this second, more resilient version of the utility steps in:

Code language
.center-xy {
  display: flex;

.center-xy > *:only-child {
  margin: auto;

Good ol’ Flexbox and its flexibility is here to save the day. Yes, there’s a tiny bit of extra CSS, but it’s serving a useful purpose. Let’s break it down:

  • We set the utility to use display: flex instead of using display: grid.
  • The direct descendant has margin: auto which thanks to the Flexbox parent, will push itself into the center. Robin Rendle wrote a great explainer of this on CSS-Tricks.
  • The :only-child pseudo-selector means that the auto margin only gets applied if—you guessed it—there’s only one child. Perfect.

It’s worth noting that both of these techniques require the parent to have at least some height to work with. That’s why I’ve set a min-height on both examples.

Wrapping up permalink

There’s probably only a handful of cases where this utility is genuinely useful. The two that spring to mind are a hero unit and a CodePen demo. I use the grid approach extensively on CodePen. Still—even though this isn’t the most portable of utilities, it’s still useful to have in your toolbelt—especially as the flex version supports around 95% of browsers.

If you do end up using this utility, let me know on Twitter. I’d love to see these utilities provide real value for people.

Hello, I’m Andy and I’ll help you build fast & visually stunning websites.

I am currently setting up a new creative agency called Set Creative Studio and we are taking on projects for 2022, so if you have a project in mind, get in touch.