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 {
text-align: center;
}
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;
}
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:
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:
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;
}
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;
}
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.)
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;
}
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;
}
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; */
}
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%);
}
Do you care if the element stretches the height of the container?
If you don’t, you just need the content inside vertically centered, using tables or CSS display to make elements into tables can do the trick.
Can you use flexbox?
No big surprise, this is a lot easier in flexbox.
.parent {
display: flex;
flex-direction: column;
justify-content: center;
}
You can also get centering in flexbox using margin: auto;
on the child element.
Both Horizontally & 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;
}
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%);
}
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;
}
Can you use grid?
This is just a little trick (sent in by Lance Janssen) that will pretty much work for one element:
body, html {
height: 100%;
display: grid;
}
span { /* thing to center */
margin: auto;
}
Conclusion
You can totally center things in CSS.
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.
Excellent tricks!
I tried to apply some of them in my responsive template. But here it doesn’t work as expected. The problem is:
1. I have 4 floating divs
In responsive parts the width of boxes are set to 49%, resp. 100% and all boxes are floating left.
I tried to make all boxes of the same height. In full width of the page the style
works fine. But on narrower displays the boxes responsivity is ignored and they stay always 4 in one row.
What’s wrong here?
You can also use absolute positioning this way :
See the Pen Vertical margin: auto by sodawillow (@sodawillow) on CodePen.
Some time ago I collected 24 different cases of “centering with css”
http://ksesocss.blogspot.com/2012/05/centrando-al-centro-con-css-16-maneras.html
Spanish blog, but code is code
How good is it to make this?
It didn’t work so well in Opera, but I liked de concept.
http://codepen.io/sodawillow/pen/yqnaC/ :-p it seems to work in opera here (win) :)
Yeah! Sure…
I forgot one thing: using
min-height
instead. No fixed height doesn’t work.Thank’s
Just wanted to add lightbox (absolute) centering to the mix for horizontal for anyone it helps
having the parent be display:table; and the child as display:table-cell;vertical-align:middle; also has a place in the potential solutions.
Thanks! I’m planning on using this a lot :)
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 :/
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.
Appearntly there is a fix by adding preserve-3d to the parent.
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.
Buried for tone.
A terrible reason to bury a perfectly reasonable comment.
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.
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.
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…
Excellent guide! Small mistake though: You used “were” instead of “where” under Vertical > Inline > Single Line.
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)
Ah, I just wrote about the damn blurred thing. Thank you for this useful 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.
Complete guides are very useful. Thanks a lot for this excellent and clear overview! Bookmarked :-)
Another way to horizontally centering unknown width element such as
<button>
without relying on parentEven though I find it the most elegant solution, the vertical positioning with translate(-50%) produces blurred content in Chrome on Windows, multiple versions.
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.
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 adisplay: inline-block
element? What if that solution is not possible?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.
You can also use the line-height technique for multiple lines too and it has better browser support –
Actually, that’s just one line/container with multiple lines inside. If you want multiple lines/container it breaks.
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.FWIW, maybe CSS intrinsic sizing might be an (futuristic) alternative to horizontally centering for block elements?
In the future, certainly. Right now, browser support for intrinsic sizing isn’t bad for
width
, but support forfit-content
onheight
is awful.It would be groovy if you went over browser compatibility for each method!
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”
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 withletter-spacing: normal
on the centered element.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.
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.
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?
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!
You, sir, deserve a thumbs up!
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!
I love this site so much! I’ve solved many CSS problems by coming here! Thank you Chris!
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
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!Thanks a lot for your great information. It’s a must read information for CSS beginner.
“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
:)
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
cool stuff, i like to read your blogs
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.
Thanks for the tips, I also like this method that will also work on IE8:
It’s based on inline-block and the use of pseudo-element.
The line height option for vertical centering works great.
I’m not understanding, though, when to use min-height. If I’m setting a fixed height and line height for a full-width toolbar at the top, would responsiveness be an issue?
Thanks for the tutorial!