Centering: The Newest Coolest Way vs. The Oldest Coolest Way

Avatar of Chris Coyier
Chris Coyier on

📣 Freelancers, Developers, and Part-Time Agency Owners: Kickstart Your Own Digital Agency with UACADEMY Launch by UGURUS 📣

This isn’t a comprehensive guide to centering things. We have that!

This is just a little observation about old and new. One of the trickier things related to centering in CSS is when you need to center both vertically and horizontally and you don’t know the width or height of what you are centering. Vertical centering being the extra tricky of the two.

Believe it or not, there was a way to do that even in IE 8. The trick was taking advantage of display: table; and that tables had this other property, vertical-align: middle;, which could be used for vertical centering.

Say all you wanted to do was center a sentence perfectly in the middle of the browser window:

...
<body>
  <span>
    Centered vertically and horizontally.
  </span>
</body>
...

You could do that like this:

html, body {
  margin: 0;
  height: 100%;
}
body {
  display: table;
  width: 100%;
}
body > span {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}

That might be the oldest trick in the Book of CSS Centering. Here it is working in IE 8:

Today we have more modern layout methods. Flexbox! CSS grid!

Here’s accomplishing the same thing with the most modern methods available:

body {
  display: grid;
  height: 100vh;
  margin: 0;
  place-items: center center;
}

We don’t even need to touch the span there! This is so cutting edge, in fact, that Microsoft Edge, which supports CSS grid, doesn’t support place-items yet. You’d have to use align-items: center; and justify-content: center; instead.

Always movin’.