Centering content on the web has been notoriously difficult. Any time something is difficult, you'll find many half-solutions that work for some situations but not others, like these:
text-align: center
, which is set on the parent and centers its inline children, but only horizontallymargin: auto
, which is set on the element itself but only centers the element horizontally and only if its width is not auto
.Flexbox washes away the years of pain. You can center both horizontally and vertically with just a few CSS properties. Suppose you want to center this heart emoji in the viewport:
You could make the top-level body element be a flex parent, but nesting content in a semantically neutral container element is a common practice. This container serves as the flex parent:
Since we want the heart in the center of the viewport, the container must fill the viewport. The body's margin also needs to go away:
Centering on the main axis is done with justify-content
. Centering on the cross axis is done with align-items
. Both support the value center
:
And there it is: two-dimensional centering with just a few lines of CSS. Your web developer forebears are jealous.
It doesn't really matter what the direction of flow is, since you want to center on both axes. So, you don't need to set flex-direction
.