Grow your CSS skills. Land your dream job.

Centering in CSS: A Complete Guide

Published by Chris Coyier

Centering things in CSS is the poster child of CSS complaining. Why does it have to be so hard? They jeer. I think the issue isn't that it's difficult to do, but in that there so many different ways of doing it, depending on the situation, it's hard to know which to reach for.

So let's make it a decision tree and hopefully make it easier.

I need to center...

Horizontally

Is it inline or inline-* elements (like text or links)?

You can center inline elements horizontally, within a block-level parent element, with just:

.center-children {
  text-align: center;
}

See the Pen Centering Inline Elements by Chris Coyier (@chriscoyier) on CodePen.

This will work for inline, inline-block, inline-table, inline-flex, etc.

Is it a block level element?

You can center a block-level element by giving it margin-left and margin-right of auto (and it has a set width, otherwise it would be full width and wouldn't need centering). That's often done with shorthand like this:

.center-me {
  margin: 0 auto;
}

See the Pen Centering Single Block Level Element by Chris Coyier (@chriscoyier) on CodePen.

This will work no matter what the width of the block level element you're centering, or the parent.

Note that you can't float an element to the center. There is a trick though.

Is there more than one block level element?

If you have two or more block-level elements that need to be centered horizontally in a row, chances are you'd be better served making them a different display type. Here's an example of making them inline-block and an example of flexbox:

See the Pen Centering Row of Blocks by Chris Coyier (@chriscoyier) on CodePen.

Unless you mean you have multiple block level elements stacked on top of each other, in which case the auto margin technique is still fine:

See the Pen Centering Row of Blocks by Chris Coyier (@chriscoyier) on CodePen.

Vertically

Vertical centering is a bit trickier in CSS.

Is it inline or inline-* elements (like text or links)?

Is it a single line?

Sometimes inline / text elements can appear vertically centered, just because there is equal padding above and below them.

.link {
  padding-top: 30px;
  padding-bottom: 30px;
}

See the Pen Vertically Centering Text by Chris Coyier (@chriscoyier) on CodePen.

If padding isn't an option for some reason, and you're trying to center some text that you know will not wrap, there is a trick were making the line-height equal to the height will center the text.

.center-text-trick {
  height: 100px;
  line-height: 100px;
  white-space: nowrap;
}

See the Pen Centering a line with line-height by Chris Coyier (@chriscoyier) on CodePen.

Is it multiple lines?

Equal padding on top and bottom can give the centered effect for multiple lines of text too, but if that isn't going to work, perhaps the element the text is in can be a table cell, either literally or made to behave like one with CSS. The vertical-align property handles this, in this case, unlike what it normally does which is handle the alignment of elements aligned on a row. (More on that.)

See the Pen Centering text (kinda) with Padding by Chris Coyier (@chriscoyier) on CodePen.

If something table-like is out, perhaps you could use flexbox? A single flex-child can be made to center in a flex-parent pretty easily.

.flex-center-vertically {
  display: flex;
  justify-content: center;
  flex-direction: column;
  height: 400px;
}

See the Pen Vertical Center Multi Lines of Text with Flexbox by Chris Coyier (@chriscoyier) on CodePen.

Remember that it's only really relevant if the parent container has a fixed height (px, %, etc), which is why the container here has a height.

If both of these techniques are out, you could employ the "ghost element" technique, in which a full-height pseudo element is placed inside the container and the text is vertically aligned with that.

.ghost-center {
  position: relative;
}
.ghost-center::before {
  content: " ";
  display: inline-block;
  height: 100%;
  width: 1%;
  vertical-align: middle;
}
.ghost-center p {
  display: inline-block;
  vertical-align: middle;
}

See the Pen Ghost Centering Multi Line Text by Chris Coyier (@chriscoyier) on CodePen.

Is it a block-level element?

Do you know the height of the element?

It's fairly common to not know the height in web page layout, for lots of reasons: if the width changes, text reflow can change the height. Variance in the styling of text can change the height. Variance in the amount of text can change the height. Elements with a fixed aspect ratio, like images, can change height when resized. Etc.

But if you do know the height, you can center vertically like:

.parent {
  position: relative;
}
.child {
  position: absolute;
  top: 50%;
  height: 100px;
  margin-top: -50px; /* account for padding and border if not using box-sizing: border-box; */
}

See the Pen Center Block with Fixed Height by Chris Coyier (@chriscoyier) on CodePen.

Is the element of unknown height?

It's still possible to center it by nudging it up half of it's height after bumping it down halfway:

.parent {
  position: relative;
}
.child {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

See the Pen Center Block with Fixed Height by Chris Coyier (@chriscoyier) on CodePen.

Can you use flexbox?

No big surprise, this is a lot easier in flexbox.

.parent {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

See the Pen Center Block with Unknown Height with Flexbox by Chris Coyier (@chriscoyier) on CodePen.

Both Horizontally and Vertically

You can combine the techniques above in any fashion to get perfectly centered elements. But I find this generally falls into three camps:

Is the element of fixed width and height?

Using negative margins equal to half of that width and height, after you've absolutely positioned it at 50% / 50% will center it with great cross browser support:

.parent {
  position: relative;
}

.child {
  width: 300px;
  height: 100px;
  padding: 20px;

  position: absolute;
  top: 50%;
  left: 50%;

  margin: -70px 0 0 -170px;
}

See the Pen Center Block with Fixed Height and Width by Chris Coyier (@chriscoyier) on CodePen.

Is the element of unknown width and height?

If you don't know the width or height, you can use the transform property and a negative translate of 50% in both directions (it is based on the current width/height of the element) to center:

.parent {
  position: relative;
}
.child {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

See the Pen Center Block with Unknown Height and Width by Chris Coyier (@chriscoyier) on CodePen.

Can you use flexbox?

To center in both directions with flexbox, you need to use two centering properties:

.parent {
  display: flex;
  justify-content: center;
  align-items: center;
}

See the Pen Center Block with Unknown Height and Width with Flexbox by Chris Coyier (@chriscoyier) on CodePen.

Conclusion

You can totally center things in CSS.

Comments

  1. Good idea! I like the concept of this article and also the show/hide structure. I applaud you, sir.

    However, I think you’re missing the spirit behind the classic “centering is hard” complaint in a couple of places, which, at least for me, always comes back to not knowing the height of the elements.

    1) Your display: table-cell fix relies on knowing the height of the child element.

    2) In your “is it block level” -> “is the element of unknown height” you proceed to give the parent an explicit height. To me, that defeats the purpose of trying to handle the unknown-height scenario. If I don’t know the height of the child, it’s quite common for me to also not know the height of the parent.

    3) In your “both hor & vert example” where the height is unknown, it’s a little weird to have the child be pos: absolute and imply that this is no big deal. I think pos: absolute is a major caveat when laying things out, since it can have the unintended consequence of having elements layer over one another.

    4) Also, in that same pen, the element fails to stay vertically centered if it has a sibling that stretches the vertical height of the parent.

    Regardless, I still really like the idea of this –it’s sorely needed. I just think it would be improved if you acknowledged some of the caveats that I think are at the root of the complaint you’re trying to dismiss.

    • 1) It doesn’t actually. I updated the example to put the height on the table instead.

      2) Vertical centering is only relevant if the parent has a set height. If the parent doesn’t have a set height, what are you centering within? Even if the answer is “the entire page”, then you need to set the height of (probably) both html, body

      3) That’s fair. It’s just one example. In my experience, if you’re trying to center something both ways like that, it’s probably a modal, in which the absolute (or fixed) positioning is going to be used. If it’s not, you can combine any of the other techniques as needed. And there is always flexbox which I covered a bunch.

      4) Demo me on this one? I’m having a hard time picturing/reproducing.

    • Hey Chris! Thanks for the reply.

      Re #1: I feel like we’re missing each other on this one. The first thing I did when I looked at the pen was delete the HTML table, since that’s not realistic/preferred for most of my use cases, though maybe I am being overly table-phobic there. Regardless, that leaves the div html, which indeed does have an explicit height, which is what is powering the vertical centering. Result: http://codepen.io/anon/pen/xIvqh

      Re #2: I actually am on the same track here as the commenter you just buried for tone. Let’s say I want to vertically center two inline-block siblings of different height: http://codepen.io/anon/pen/Cjdeo

      Re #3: Truce.

      Re #4: Really the same point as #2, although I didn’t catch that pos: absolute was part of this one as well, which does kind of distract from the height issue ( the fact that the elements are layered on top of each other is a more eye-catching layout bug than the fact that they’re not vertically centered.): http://codepen.io/anon/pen/rjflG .

    • Sorry, I am kind of misinterpreted, misrepresenting what you are doing with #1. Truce there, as well.

  2. Permalink to comment#

    You can also use absolute positioning this way :

    See the Pen Vertical margin: auto by sodawillow (@sodawillow) on CodePen.

  3. Permalink to comment#

    How good is it to make this?

    {
    position: absolute;
    top: 0; left: 0; right: 0; bottom: 0;
    margin: auto;
    width: _n_;
    height: _n_;
    }
    

    It didn’t work so well in Opera, but I liked de concept.

  4. Just wanted to add lightbox (absolute) centering to the mix for horizontal for anyone it helps

  5. mark
    Permalink to comment#

    having the parent be display:table; and the child as display:table-cell;vertical-align:middle; also has a place in the potential solutions.

  6. Zeke Y
    Permalink to comment#

    Thanks! I’m planning on using this a lot :)

  7. Permalink to comment#

    The issue when using thee transform property and a negative translate of 50% in both directions (when centering both horizontally and vertically an element of unknown width and height) is that is the result will often be blurred (depending on the exact size of the first parent with a position non static) when the result of the -50% is not an integer.

    I guess the blur is invisible on retina screens but on most people’s screen it’s awful :/

    • shshaw
      Permalink to comment#

      Agreed. I’m not a fan of using transforms on text based content. Browsers have gotten better about the rendering, but you still end up with fuzzy, hard-to-read text a lot of the time.

    • Mazurka
      Permalink to comment#

      Appearntly there is a fix by adding preserve-3d to the parent.

  8. ewfewf
    Permalink to comment#

    Considering this article is called complete guide, i would have hoped to read more about common problems like centering of floats, align list element icons in multi line list elements etc. rather than reading about pie in the sky flexbox stuff.
    But to answer the question: “If the parent doesn’t have a set height, what are you centering within? ” The container that is expanded by it’s tallest child, where the other children need to be vertical aligned, duh.

  9. Chris – you may want to add that to horizontally center block level elements with margin: 0 auto; it has to have a fixed size. You don’t mention that specifically.

    • ergergerg
      Permalink to comment#

      Not necessary since block elements are full width by default and don’t need horizontal alignment when the fill up the whole available space anyway.

  10. Hotdog Johnson
    Permalink to comment#

    Nothing about vertical-align, eh. The most worthless property ever.

    Why? Why is it so confusing, difficult, and hack-y to center some content within a fixed-height block? It continues to make no sense to me. I’m so tired. I’m so tired.

    • It’s mentioned under Vertically -> Multiple Lines.

      But absolutely agreed that the process is a lot clunkier than it should be! The concept is so basic, but look how many potential solutions we have…

  11. Permalink to comment#

    Excellent guide! Small mistake though: You used “were” instead of “where” under Vertical > Inline > Single Line.

  12. You could add the “half pixel” fix for the vertical “translate” hack, http://zerosixthree.se/vertical-align-anything-with-just-3-lines-of-css/ (update from April, 2014)

    • Stollz
      Permalink to comment#

      Ah, I just wrote about the damn blurred thing. Thank you for this useful comment!

    • Veronique
      Permalink to comment#

      Thanks for the link for the half-pixel fix . I was always trying to avoid it by making sure my line-height and all padding was in pixels and even numbers (that way the height is always an even number). But the fix you gave makes this much easier.

  13. Permalink to comment#

    Complete guides are very useful. Thanks a lot for this excellent and clear overview! Bookmarked :-)

  14. Permalink to comment#

    Another way to horizontally centering unknown width element such as <button> without relying on parent

    button {
      display: table;
      margin: 0 auto;
    }
    
  15. Stollz
    Permalink to comment#

    Even though I find it the most elegant solution, the vertical positioning with translate(-50%) produces blurred content in Chrome on Windows, multiple versions.

  16. Permalink to comment#
    div {
      display: flex;
    }
    div div {
      margin: auto;
    }
    
  17. Beautiful summary, Chris. Right into my CSS book’s webliography.

    By the by, the complaints are partly because “” was so simple and “margin: 0 auto” is such a kludge. This still is CSS at its worst.

  18. Tri Nguyen
    Permalink to comment#

    If I need to center a div of dynamic content width, I cannot use to margin: 0 auto trick. In that case, should I just convert it to a display: inline-block element? What if that solution is not possible?

    • qwdqw
      Permalink to comment#

      DIVs don’t shrink to fit (unless floated), so if you don’t add a width it will always be full width, where you don’t need horizontal centering. So, you will have to add a width anyway. Or use inline-blick as you already said.

  19. Sean Jacob
    Permalink to comment#

    You can also use the line-height technique for multiple lines too and it has better browser support –

    .box { height:200px; line-height:200px;  }
    
    .middle { display:inline-block; vertical-align:middle; line-height:1.2;  }
    
    • wef
      Permalink to comment#

      Actually, that’s just one line/container with multiple lines inside. If you want multiple lines/container it breaks.

    • Sean Jacob
      Permalink to comment#

      Can you show me an example? If you want multiple containers you should put them in the .middle element instead of creating multiple .middle elements.

  20. Permalink to comment#

    FWIW, maybe CSS intrinsic sizing might be an (futuristic) alternative to horizontally centering for block elements?

    • shshaw
      Permalink to comment#

      In the future, certainly. Right now, browser support for intrinsic sizing isn’t bad for width, but support for fit-content on height is awful.

  21. Jon
    Permalink to comment#

    It would be groovy if you went over browser compatibility for each method!

    • shshaw
      Permalink to comment#

      I put together a comparison table with the browser compatibility for these different methods and a few that aren’t mentioned. See the “Comparison Table” at http://codepen.io/shshaw/full/gEiDt/

      Most all of these should work in IE8+, but transforms will only work in IE9+. There’s more information about each technique under “Other Techniques”

  22. shshaw
    Permalink to comment#

    Great roundup. Surprised there’s no mention of margin: auto as a solution for fixed width/height, though :-)

    In your “Ghost Centering” example, under Vertically > Inline > Multiple Lines, it only works right here because you have a fixed width on the inline element being centered.

    Since they are both display: inline-block, the browser automatically puts space between them. If you remove the fixed width, you end up with your content being pushed down by the ::before element, :

    A safer method of centering this way is to use ::after instead. This way the actual content won’t ever be pushed down by the pseudo element.

    You can also remove the fixed width on the content and use letter-spacing: -0.5em to prevent a gap between the pseudo element and the element being centered. Then reset with letter-spacing: normal on the centered element.

  23. Hey Chris. This is a fantastic resource. I think what would be super useful is if you added some basic guidelines as to when to use which. It’s mostly about browser compatibility, which is where I think a lot of people get hazy. Perhaps if a matrix were made where you check off the browsers you want to support and then only the relevant methods were highlighted.

    I have some ideas on how to do this using this article as the base… I should really start blogging.

  24. Permalink to comment#

    Nice post….

    This help a lot….

  25. Josh Hadik
    Permalink to comment#

    This helped me a lot. however, I’m still having trouble centering multiple divs in a line. If you have the time, please check out my site (I’m new to web development so don’t judge it to hard) My Website and take a look at the 5 circles at the top of the page… currently, they are not centered horizontally (there is more blank space on one side then the other,) I was wondering if you knew how to fix this problem so that everything is centered on the page. Thanks for your time.

  26. Great Post!

    The way you make various columns the same height, is so simple with display: flex; !

    Wish there was support for IE 9 at least.

    Does someone know of a simple “fallback” for this?

  27. Michael Bjerregaard
    Permalink to comment#

    Sweet jesus! The transform: translate(-50%, -50%); is totally awesome… I can’t believe I never thought about this. I was not aware that this was so well supported.

    Life just got better :-)

    Thx Chris for serving a very useful guide!

  28. Matt
    Permalink to comment#

    You, sir, deserve a thumbs up!

  29. I personally have never used value “0” when using margin. I’ve always used margin:auto;, that’s it. Never have I had any issues whatsoever leaving that 0 out.

    Just sayin’.

    Awesome decision tree idea!

  30. Amanda
    Permalink to comment#

    I love this site so much! I’ve solved many CSS problems by coming here! Thank you Chris!

  31. Permalink to comment#

    Hi Chris, great article as always and very useful !
    Careful, the CodePen examples are shifted from one branch/paragraph to another (e.g. : ghost elements example should be in Vertically/inline/multiple lines, is actually in Vertically/block/do you know height)
    Cheers, Pierre

  32. Well organized article. Centering in CSS is always a pain for the web developers. This guide is a life saver for them!

    I always used the line-height for vertical alignment for texts. Otherwise, I think of using Javascript to align elements while loading the page ;-) but that’s not the right way! Thanks for the article!

  33. Rajesh
    Permalink to comment#

    Thanks a lot for your great information. It’s a must read information for CSS beginner.

  34. andychups
    Permalink to comment#

    “Is the element of unknown width and height?” – i preffer bulletproof, oldschool solution with table http://codepen.io/andychups/pen/CDLxK.

    By the way, i like this tweet: “The easiest way to vertically center something in CSS is to close your laptop and go to the bar.” @bleikamp

    :)

  35. Hi Chris,

    Do you know if there are any options to vertically center text based on its x-height instead of the entire height of the text? When the container is slightly larger than the font-size this might be preferred.

    The option I could think of only works for a single line of text and consists of adding a pseudo element with height set to the height of its container and vertical-align: middle; applied.

    See http://codepen.io/ckuijjer/pen/nIGCt

  36. Krish
    Permalink to comment#

    cool stuff, i like to read your blogs

  37. Nice one. There is always a bunch of different options, but I think the frustration boils down to no fool proof way of vertically centring something with decent browser support and not adding a some sort of extra markup. Always feels a bit hacky and dirty whichever way I end up going, but I guess vertical centring isn’t alone there.

    If the height of the parent is known, I usually add that as a line-height on that parent and inline block the child, so the height of the child can be variable. If the height of the parent is unknown I usually absolutely positioned child and move it around as need be.

Leave a Comment

Posting Code

  • Use Markdown, and it will escape the code for you, like `<div class="cool">`.
  • Use triple-backticks for blocks of code.
    ``` 
    <div>
      <h1>multi-line block of code</h1>
      <span>be cool yo.</span>
    </div>
    ```
  • Otherwise, escape your code, like <code>&lt;div class="cool"&gt;</code>. Markdown is just easier though.

Current ye@r *

*May or may not contain any actual "CSS" or "Tricks".