Two simple methods to vertically and horizontally center content with CSS
— 3 minute read
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 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:
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.
Hi 👋 I’m Andy, a freelance web designer
I’m currently looking to book web design and front-end development projects from September 2019, onwards.