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>, with min-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.

👋 Hi! I'm Rem, a Web developer since 1998, in Japan since 2006. I'm the author of dress.css and Scrollerful. As you can imagine, my experience is varied, including the early days of the Web being a webmaster writing HTML files and scripts in Perl, saved on floppy disks using Notepad, to now being a tech lead for a team, writing CSS with Tailwind or JavaScript for both the backend and frontend in Neovim. I love photography, typography, and colour theory. Strangely enough, my love for print graphic design was what got me into web development. So, yes, I have a few stories to tell and tips to give, and I'm writing some of them, sometimes, here, on RÉMINO Bits.