Menu Search
Jump to the content X X
Smashing Conf New York

We use ad-blockers as well, you know. We gotta keep those servers running though. Did you know that we publish useful books and run friendly conferences — crafted for pros like yourself? E.g. upcoming SmashingConf Barcelona, dedicated to smart front-end techniques and design patterns.

Absolute Horizontal And Vertical 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! But actually (spoiler alert!) absolute centering only requires a declared height*1 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 article2.

There, Simon3 linked to this jsFiddle4 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 some5 other6 sources for this method.

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

Leave a comment on CodePen107, Smashing Magazine8, or message @shshaw9 on Twitter if you have any additional features or suggestions.

Find additional demos, a comparison table, and more on CodePen107.

Advantages: Link

  • Cross-browser (including IE8-10)
  • No special markup, minimal styles
  • Responsive with percentages and min-/max-
  • Use one class to center any content
  • Centered regardless of padding (without box-sizing!)
  • Blocks can easily be resized
  • Works great on images

Caveats: Link

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

Browser Compatibility: Link

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.

Explanation Link

After researching specs and documentation, this is my understanding of how Absolute Centering works:

  1. In the normal content flow13, margin: auto; equals ‘0’ for the top and bottom.
    W3.org14: If ‘margin-top’, or ‘margin-bottom’ are ‘auto’, their used value is 0.
  2. position: absolute; breaks the block out of the typical content flow, rendering the rest of the content as if that block weren’t there.
    Developer.mozilla.org15: …an element that is positioned absolutely is taken out of the flow and thus takes up no space
  3. Setting top: 0; left: 0; bottom: 0; right: 0; gives the browser a new bounding box for the block. At this point the block will fill all available space in its offset parent, which is the body or position: relative; container. Developer.mozilla.org1716: For absolutely positioned elements, the top, right, bottom, and left properties specify offsets from the edge of the element’s containing block (what the element is positioned relative to).
  4. Giving the block a width or a height prevents the block from taking up all available space and forces the browser to calculate margin: auto based on the new bounding box. Developer.mozilla.org1716: The margin of the [absolutely positioned] element is then positioned inside these offsets.
  5. Since the block is absolutely positioned and therefore out of the normal flow, the browser gives equal values to margin-top and margin-bottom centering the element in the bounds set earlier.
    W3.org18: If none of the three [top, bottom, height] are ‘auto’: If both ‘margin-top’ and ‘margin-bottom’ are ‘auto’, solve the equation under the extra constraint that the two margins get equal values. AKA: center the block vertically

Absolute Centering appears to be the intended use for margin: auto; based on the spec and should therefore work in every standards compliant browser.

TL;DR: Absolutely positioned elements aren’t rendered in the normal flow, so margin: auto; centers vertically within the bounds set by top: 0; left: 0; bottom: 0; right: 0;.

Within Container Link

.Center-Container {
  position: relative;
}

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

With Absolute Centering, you can place your content block inside of a position: relative container to align the block within the container!

The rest of the demos will assume these styles are already included and will provide add-on classes to implement various features.

Absolute Center,
Within Container. Link

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

Within Viewport Link

.Absolute-Center.is-Fixed {
  position: fixed;
  z-index: 999;
}

Want the content block centered in the viewport? Set it to position: fixed and give it a high z-index, like the modal on this page.

  • Mobile Safari: The content block will be centered vertically in the whole document, not the viewport, if it is not within a position: relative container.

Offsets Link

.Absolute-Center.is-Right {
  left: auto; right: 20px;
  text-align: right;
}

.Absolute-Center.is-Left {
  right: auto; left: 20px;
  text-align: left;
}

If you have a fixed header or need to add other offsets, simply add it in your content block’s styles like top: 70px;. As long as margin: auto; is declared, the content block will be vertically centered within the bounds you declare with top left bottom and right.

You can also stick your content block to the right or left while keeping it vertically centered, using right: 0; left: auto; to stick to the right or left: 0; right: auto; to stick to the left.

Vertical Center,
Align Right. Link

This box is absolutely centered vertically within its container, but stuck to the right with
right: 0; left: auto;

Footnotes Link

  1. 1 https://www.smashingmagazine.com/2013/08/09/absolute-horizontal-vertical-centering-css/2#Height
  2. 2 http://designshack.net/articles/css/how-to-center-anything-with-css
  3. 3 http://designshack.net/articles/css/how-to-center-anything-with-css/#comment-684580538
  4. 4 http://jsfiddle.net/mBBJM/1/
  5. 5 http://www.vanseodesign.com/css/vertical-centering/
  6. 6 http://www.student.oulu.fi/~laurirai/www/css/middle/
  7. 7 http://codepen.io/shshaw/details/gEiDt
  8. 8 https://www.smashingmagazine.com/2013/08/09/absolute-horizontal-vertical-centering-css/#comments
  9. 9 http://twitter.com/shshaw
  10. 10 http://codepen.io/shshaw/details/gEiDt
  11. 11 https://www.smashingmagazine.com/2013/08/09/absolute-horizontal-vertical-centering-css/2#Height
  12. 12 #Overflow
  13. 13 http://taligarsiel.com/Projects/howbrowserswork1.htm#Layout
  14. 14 http://www.w3.org/TR/CSS2/visudet.html#normal-block
  15. 15 https://developer.mozilla.org/en-US/docs/Web/CSS/position#Absolute_positioning
  16. 16 https://developer.mozilla.org/en-US/docs/Web/CSS/position#Notes
  17. 17 https://developer.mozilla.org/en-US/docs/Web/CSS/position#Notes
  18. 18 http://www.w3.org/TR/CSS2/visudet.html#abs-non-replaced-height
SmashingConf New York

Hold on, Tiger! Thank you for reading the article. Did you know that we also publish printed books and run friendly conferences – crafted for pros like you? Like SmashingConf Barcelona, on October 25–26, with smart design patterns and front-end techniques.

↑ Back to top Tweet itShare on Facebook

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

  1. 1

    This is a mystic quest for lot’s of webdesigner !
    Thanks for sharing those informations.

    11
  2. 3

    Martin LeBlanc

    August 9, 2013 11:34 pm

    Guides like this saves a lot of time. Unfortunately CSS is not as intuitive as it should be.

    6
  3. 4

    Genius technique thanks :-)

    1
  4. 5

    Kim Andre Ottesen

    August 9, 2013 11:42 pm

    Great and flexible technique I’ve used quite a lot, e.g. when combined with Flexslider to create a sleek centered gallery.

    0
  5. 6

    Very useful article! My favorite technique is how Magnific Popup centers content, as its kept responsive and scrollbar is triggered when height is bigger then window, there was an article on SM – http://coding.smashingmagazine.com/2013/05/02/truly-responsive-lightbox/

    2
  6. 7

    Rahul Choubey

    August 10, 2013 12:46 am

    This gives so much relief…thanks for sharing!

    1
  7. 8

    Great resource, thanks for sharing. Alignments are always a nightmare! :D

    1
  8. 9

    I wonder what would be the best technique right now, to place vertically and horizontally centered text on image thumbnails (on hover) in responsive layouts, since we normally only set width on those elements, to fit the grid.

    1
  9. 10

    Henry Roberts

    August 10, 2013 2:03 am

    I was overwhelmed with the urge to try this out as soon as I saw it. Ten minutes later, I have this: http://instadesign.co.uk/absolutcenter/

    Thanks so much, I shall not be forgetting this!

    5
    • 11

      It’s not perfect on chrome… Try to change browsers height to smaller than the content. You will see that TOP of the page is getting CROPPED!

      0
    • 12

      I have to admit it took me a couple of seconds to understand it… :(

      0
  10. 13

    It’s smashing!thank you

    1
  11. 14

    That’s what browsers use to center standalone images.. since the dawn of time. Never looked at their code? :)

    1
  12. 15

    Just use a table, idiot.

    -36
    • 16

      Jeff Golenski

      August 12, 2013 8:01 am

      LOL. I haven’t thought of that method since 2001. It. Just. Makes. Sense.

      0
      • 17

        Display:table; height:100% (and parents with height:100%) is the solution: I’m not going to argue with MDO from Bootstrap on this one. (check the examples: Cover)

        -2
  13. 18

    Irina Petculescu

    August 10, 2013 3:14 am

    great roundup, thanx

    1
  14. 19

    But no height: auto for divs, which is where it would REALLY be interesting and helfpul. It’s a good technique, no doubt, but it rarely comes to help. I’ve been doing top: 50%; height: X; margin-top: X/2; for the most part, and it works.

    For height: auto, I’ve been doing jquery events to change the margin-top on render and on window resize, and it works, but it requires javascript, which sucks.

    1
    • 20

      If you need height: auto, read over the Variable Height section for some tips, or you can try one of the alternative methods, like Table-Cell that will get it done without needing Javascript!

      1
  15. 21

    Richard Denton

    August 10, 2013 4:03 am

    Thank-you! Goodbye, negative margins!

    -1
  16. 22

    This is neat, but isn’t going to replace the table-cell method for me. I’ve been using table cell for a long time and have the markup/CSS snippets in my toolbox, so the one caveat isn’t concerning enough to trade for cross browser performance. Maybe I’m just not adventurous enough…

    1
  17. 23

    Bali Ram Vyas

    August 10, 2013 4:37 am

    Very useful for all designer/developer. Thanks for sharing it.

    1
  18. 24

    Very useful….
    Thanks for this…… :)

    -1
  19. 25

    Gerob Kimball

    August 10, 2013 6:43 am

    Great article! These type of layout things can be troublesome when you are first getting started with web development. I was reminded of this recently talking to a junior web designer who just started and was expressing his frustration at getting things lined up right. I made sure to share this with him. Thanks!

    -1
  20. 26

    Mark Petherbridge

    August 10, 2013 12:03 am

    Thank you for this wonderful and concise solution to all my hacky code. I do believe that you are about to save me a lot of time, and for that kudos.

    0

↑ Back to top