Absolute Centering – CodePen

Absolute Centering in CSS

We’ve all seen margin: 0 auto; for horizontal centering, but margin: auto; has refused to work for vertical centering… until now!

Spoiler alert : Absolute Centering only requires a declared 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.

There, Simon linked to this jsFiddle that blew every other method out of the water (the same method was also mentioned by Priit in the comments). Researching further, I had to use very specific keywords to find some other sources for this method.

Having never used this technique before, I put it to the test and discovered how incredible Absolute Centering really is.

Advantages:

  • Cross-browser (including IE8-10 without hacks!)
  • No special markup, minimal styles
  • Responsive with percentages and min-/max-
  • Centered regardless of padding (without box-sizing!)
  • Works great on images

Caveats:

  • Height must be declared (see Variable Height)
  • Recommend setting overflow: auto to prevent content spillover (see Overflow)
  • Doesn’t work on Windows Phone

Browser Compatibility:

Chrome, Firefox, Safari, Mobile Safari, IE8-10.

Absolute Centering was tested and works flawlessly in the latest versions of Chrome, Firefox, Safari, Mobile Safari, and even IE8-10.
One user reported that the content is not vertically centered in Windows Phone’s browser, but otherwise this technique works as expected.
Within Container : Place your content block inside of a position : relative container to perfectly center your content within the container!

.Absolute-Center {
 width: 50%;
 height: 50%;
 overflow: auto;
 margin: auto;
 position: absolute;
 top: 0; left: 0; bottom: 0; right: 0;
 } 

Absolute Center, Within Container.

This box is absolutely centered, horizontally and vertically, within its container using position: relative Within Viewport

Absolute Centering – CodePen.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s