Author:

A passionate front-end developer who cares about CSS, JavaScript and keeping code clean and nifty.

Twitter: Follow Stephen Shaw on Twitter

Absolute Horizontal And Vertical Centering In CSS

In this article, Stephen Shaw introduces a technique for perfect horizontal and vertical centering in CSS, at any width or height. The techniques works with percentage-based width/height, min-/max- width, images, position: fixed and even variable content heights. — Ed.

We've all seen margin: 0 auto; for horizontal centering, but margin: auto; has refused to work for vertical centering... until now! But actually (spoiler alert!) absolute centering only requires a declared (variable) height and these styles.

.Absolute-Center {
  margin: auto;
  position: absolute;
  top: 0; left: 0; bottom: 0; right: 0;
}

I'm not the pioneer of this method (yet I have dared to name it Absolute Centering), and it may even be a common technique, however, most vertical centering articles never mention it and I had never seen it until I dug through the comments section of a particular article.

Read more...

↑ Back to top