Five documented approaches to centering

Adam Argyle's web.dev article treats centering as a two-axis problem: horizontal centering is generally well understood, while vertical centering remains the hard part, especially when the content's height is not known in advance. For a broader decision-tree treatment of many layout situations, CSS-Tricks' complete guide to centering covers the surrounding territory.

Argyle lays out five distinct methods, and the coverage extends to boxes whose vertical and horizontal dimensions are both unknown, along with constraints such as writing direction and multiple elements. Each technique comes with its pros and cons spelled out and demonstrated; there is also a video accompanying the post.

The preferred solution: a gentle flex

His pick among the five is what he calls "the gentle flex":

.gentle-flex {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 1ch;
}

You can always find it in my stylesheets because it's useful for both macro and micro layouts. It's an all-around reliable solution with results that match my expectations. Also, because I'm an intrinsic sizing junkie, I tend to graduate into this solution. True, it's a lot to type out, but the benefits it provides outweighs the extra code.

Smaller cases: inline content and fit-content parents

Most centering needs are far less extreme. To center inline-* elements horizontally, text-align: center; is a single line. (By inline-*, the intended values are inline, inline-block, inline-flex, inline-grid and inline-table.)

The parent of such items is another matter. The familiar margin: 0 auto; works, but a block-level parent is typically either full-width or fixed-width. Wanting it only as wide as its content usually leads to making the parent inline-* — which then requires yet another parent carrying the text-align to actually center it. Stefan Judis recently described the alternative: keep the element block-level and set width: fit-content;. The gentle flex could likely handle this case too, but it would again require an extra parent.