One-line code now beats one-line joke
“How do you center a div?” How many times did you hear that question being asked ironically or seriously?
I mean, yeah, it’s certainly a pain to centre something vertically on a webpage. There’s no denying that.
Luckily, in 2024, like the title of this article says, we’re finally at a point where we can do this with one simple line of CSS:
html {
align-content: center; /* <- THE MAGIC LINE! Set it on the container block. */
min-height: 100%; /* Must set min height of root element. */
}
body {
max-width: 30rem;
margin: 0 auto; /* Set auto inline margins to align a block horizontally. */
}
Look out for these!
You may be thinking you need display: flex or display: grid, but nope! It now works in most modern browsers with display: block elements as well (not just <html>).
However, there are some gotchas you need to keep in mind:
- To centre a block horizontally, you’ll still need
margin-inline: auto;. - To centre text, evidently, you must use
text-align: center;. - When you’re aligning the content vertically of the whole page, you need to set the height of your root element,
<html>, withmin-height: 100%;, or whatever is most appropriate.
Also, if you’re curious, no, justify-content doesn’t work on block layout elements.
But hey, despite the above, this is far better than all the hacks and tricks with flexbox, grid, tables, spacers, and whatnot us experienced web developers had to ensure for decades. ;)
Demo
Here’s a demo on CodePen showing vertical alignment with align-content: center; in all its glory.
