
How to Center in CSS - plurby
http://howtocenterincss.com/
======
lisper
The mere fact that a site like this can exist and not be a joke is proof that
CSS is still badly broken. I should be able to center things by writing:

    
    
        foo {
          align: center;
          valign: center;
        }

~~~
pcwalton
You're in luck.

    
    
        foo {
            display: flex; /* opt into the new box model */ 
            justify-content: center; /* "align" */
            align-items: center; /* "valign" */
        }
    

Vendor prefixes may or may not ruin your day (for now), but the spec is there
and is exactly what you want. CSS is no longer "badly broken" if that's your
metric.

~~~
tedunangst
Sweet. I figure only 15 more years until we get two column layouts working,
and then we'll finally be able to publish like it's 1979.

~~~
pcwalton
CSS multicolumn layout is four years old. It's implemented in all the major
browser engines, and many popular sites like Wikipedia use it.
[http://www.w3.org/TR/css3-multicol/](http://www.w3.org/TR/css3-multicol/)

~~~
rsanek
Only partially. You usually have to use browser prefixes to get it to
function.
[http://caniuse.com/#feat=multicolumn](http://caniuse.com/#feat=multicolumn)

~~~
nailer
Add Autoprefoxer in your build process and never type them again.

~~~
yoran
Or use Bourbon mixins ([http://bourbon.io/docs/](http://bourbon.io/docs/)) if
you use SASS.

~~~
nailer
SASS mixins are great, but Autoprefixer is better for prefixes: it looks the
same as writing actual CSS (just with no prefixes) and has no cognitive
overhead during editing. Compare the Bourbon mixin:

    
    
        @include background(linear-gradient(red, green) left repeat);
    

to autoprefixer:

    
    
        background: linear-gradient(red, green) left repeat;

~~~
Nilzor
AAAAaaand we're back to 7 solutions to a simple problem

~~~
freshyill
How so? Autoprefixer allows you to just write spec CSS and let _it_ worry
about prefixes.

------
carsongross
I am reminded of one of my favorite tweets of all time:

“The easiest way to vertically center something in CSS is to close your laptop
and go to the bar.” - @jakeboxer

[https://twitter.com/thedaniel/status/414123893830336513](https://twitter.com/thedaniel/status/414123893830336513)

~~~
peterjmag
This one cracked me up too:

    
    
        “How to choose between rem and em”
        
        1. question css
        2. question your life
        3. throw away laptop
        4. scamper into forest
    

[https://twitter.com/iamdevloper/status/587651586350002176](https://twitter.com/iamdevloper/status/587651586350002176)

------
DiThi
As others said, flexbox is a complete replacement for all layour hacks in CSS.
This site helped me understand flexbox:
[http://flexboxin5.com/](http://flexboxin5.com/)

Browser support:
[http://caniuse.com/#feat=flexbox](http://caniuse.com/#feat=flexbox)

~~~
supercoder
That site is completely broken in Safari. Don't think we're ready for flexbox
just yet.

~~~
yAnonymous
It's not the site that's broken, but Safari.

~~~
scotty79
What's broken is not Safari but people who buy Macs. ... I can't go any
deeper. Still I'd like my site to look good to a meaningful market share.

~~~
yAnonymous
True, but I wouldn't say 4% is a meaningful market share, so fuck Safari. It's
the new Internet Explorer.

Leaving the sites broken in Safari (and maybe adding a notice that explains
why it's broken) also helps keeping it at 4%.

~~~
supercoder
For starters the market share is far higher than 4% on the desktop, and even
more when looking at the mobile / tablet market.

It's more like Chrome is the new Internet Explorer, because lazy web
developers decide to only target it, so we end up with sites specific to one
web browser.

~~~
yAnonymous
Yeah, the 4% was wrong, sorry. Anyway, things seem to just work in FF and
Chrome, but Safari often requires fixing because of bugs, missing features or
Apple doing things differently for no reason. It's annoying.

And like Microsoft, they are so damn slow to release updates and older
machines don't even get any.

------
mhink
Doesn't Flexbox pretty much solve this problem? I mean, if you need to
maintain backwards compatibility this might be reasonable, but "justify-
content: center" and "align-items: center" seem to work unreasonably well for
this exact purpose.

~~~
nkozyra
Flexbox solves this problem but it's still a bit unwieldy and verbose.

~~~
sondr3
Verbose? Compared to the other solutions it's a godsend, just use the CSS-
tricks guide for it and you'll have nearly zero problems. I absolutely love it
and pretty much refuse to use anything else for layout in CSS now.

~~~
drcode
IMHO constraint systems like GSS
([http://gridstylesheets.org/](http://gridstylesheets.org/)) handle centering
in a much cleaner way. Pity that approach hasn't gotten any traction (though
some people smarter than me say it's a bad idea, so who knows what the right
answer is...)

~~~
ux-app
When I first heard of GSS I thought it was the solution to layout that we'd
all been waiting for. Unfortunately it's not all roses. It's possible, and
quite easy to inadvertently create cyclical constraint dependencies. Depending
on how your constraint solver is written this might mean that a layout will
fail or that your system will lock or crash.

I'm subscribed to a couple of constraint solver mailing lists. A common
question is "why is my constraint solver doing this...?", or "how do I massage
my constraints to achieve this...?"

With CSS You can't build a layout that 'fails' (in the sense that a solution
cannot be computed due to improperly defined dependencies), and you certainly
can't send your browser into an infinite loop by applying an incorrect style.

I still _really_ like the idea of constraint based systems, but I think they
are more suited to (web)applications rather than documents.

~~~
TeMPOraL
> _I still really like the idea of constraint based systems, but I think they
> are more suited to (web)applications rather than documents._

Which is what some people will tell you web is about when you point out to
them they're doing something weird instead of writing a document communicating
a message. Maybe it's time to separate those two use cases - web pages and web
applications - because otherwise people will keep getting confused between the
needs and problems of the two?

Anyway, GSS looks pretty cool.

------
CmdrKrool
I know the web is not print, pages are not static, user screens vary and one
shouldn't try to control everything bla bla bla, but it seems all my layout
woes ultimately boil down to difficulty in _lining things up_.

That's what 'layout' means after all, isn't it? Aligning one thing with
another, to show they're related. I'm not a classically trained graphic
designer, but doesn't any explication of visual fundamentals include
'alignment' somewhere up near its top?

Yet CSS really, really sucks at _lining things up_.

Anyone designing a better system might do well to start with the notion of
alignment as a basic primitive/operator. To be able to say, item A here ought
to line up with item B there (and if not possible, predictable behaviour C
results).

My gut feeling is that one could then derive all other types of layouts from
there. I admit that might be naive. Also, I realise that I've probably just
described constraint-based layout, but as yet I haven't tested one of its
implementations such as GSS in a real project.

~~~
talmand
As a classically trained graphic designer, I find the biggest problems to
layout is more due to the fact that the display is completely unknown. It can
range anywhere from hundreds of pixels in width/height to thousands of
width/height in pixels. Not to mention the differences in pixel densities and
orientations.

If one were to consider these problems alone, CSS works quite well for what it
was designed to do. Most designers I've discussed these problems with have
problems more in their thinking than with the tool itself. They mostly try to
apply print design thinking to web design, which simply does not work.

------
justindocanto
The table-cell solution for vertically centering text is incorrect. You need
to put that display:table-cell div inside a display:table div. It requires the
parent in order to work properly.

Example: <div class="item"><div><p>Your text here</p></div></div>

.item {display:table;} .item > div {display:table-cell;vertical-align:middle;}

I use this method on justindocanto.com to vertically center an unknown amount
of text/elements inside a div that changes its size based on the size of the
image that's inside it. Really nice technique when used correctly.

~~~
scotty79
Yes. This page gives wrong solutions for unknown size of centered block but
known sizes of container.

------
chubs
Wow CSS is unfriendly, you really realise how poor it is once you learn other
layout systems (android's XML and iOS auto layout, etc).

Wish there was another standard that could co-exist side by side on the web,
something simple enough to be implemented reliably by the browser vendors.

~~~
WalterGR
How do Android's XML and iOS's auto layout compare to Microsoft's WPF? I used
the latter around 10 years ago and found it pretty nice.

~~~
MichaelGG
Exactly. I haven't done HTML layout since circa 2000. I tried WPF about 8-9
years ago and well, it was just _simple_ to get layouts right. I'm sure
there's some reasonable reason for it, I just don't understand why browsers
couldn't do similar, or just rip off WPF.

------
tomasien
I remember when I was first learning CSS and I found out this wasn't easy. I
thought "oh my god, this learning to code stuff is gonna be HARD!"

A few years later and I don't think anything but the occasional third party
api with undocumented behavior has been nearly as hard.

------
toxican
To save people a bunch of time, here's 90% of the comments:

>Just use flexbox!

Which is great, except it isn't supported at all by IE8 or 9 and is only
partially supported in IE10 (by prefix only). Which means a lot of people
simply can't use it. I'm hesitant to use it myself, and I've got a very lax
policy on supporting old IE.

~~~
throwawaymsft
It's a business decision to limit forward progress to support browsers 3-4
major versions behind. One that multi-billion dollar companies like Google
have decided isn't worth it.

"A lot of people" = 4% on IE 8 & 9
([http://www.w3counter.com/globalstats.php](http://www.w3counter.com/globalstats.php))

~~~
toxican
Really depends on the business and their clients. If you've got a lot of
corporate clients stuck on IE8/9, why disenfranchise them? Although I will say
this has me re-considering flex.

------
bhousel
I can't think of a technology that has both saved and wasted more of my time
than CSS.

~~~
imakesnowflakes
Git

------
menssen
I often use this as an interview question for CSS people: "How would you
vertically center a box inside another box." I like it because there's like
four correct answers, each with drawbacks. The general answers, from worst to
best, are usually:

    
    
      1. margin: auto (wrong)
      2. top: 50% (mostly wrong)
      3. negative margin-top (correct if you know the size)
      4. table-cell or translateY (correct)
      5. a correct answer plus a discussion about why it has to be a hack
    

FWIW, when you set everything to "Unknown", this site tells you to use
display: table-cell. If you don't have to support IE8, I generally prefer
"top: 50%; translate-Y: -50%"

[Edited for spacing.]

------
eddd
This actually proves that CSS is broken. I just want to say: 'put this content
in the middle' nothing else. That is the reason why I am trying to avoid doing
frontend whenever possible - it just sucks. Luckily Elm([http://elm-
lang.org/Learn.elm](http://elm-lang.org/Learn.elm)) tries to solve that
problem and i hope it will get some traction very soon.

------
mambodog
This should also have an option for 'what browsers do you need to support' and
just provide flexbox output instead if you don't need to support legacy IE.

~~~
ommunist
Don't forget the need to support HTML email clients. Say, Lotus Notes.

~~~
Nemcue
Using some sort of service (i.e. Mailchimp or any of the other numerous email
sending services) surely takes care of this, no?

------
lucb1e
This looks really useful. In case the author reads this, one addition it could
use is explaining why the given css works. And, like someone else already
mentioned, indicate browser support. I haven't used this display:table-cell
before and I wonder about its support. A small thing to lookup, sure, but it
would be nice built-in. Or selecting which browsers you need to support and
using flexbox when possible.

------
pcwalton
This site doesn't seem to be suggesting absolute centering [1] when it would
be the easiest way to center things.

"margin: auto" seems to be the way that the designers of CSS 2.1 intended to
center things. 90% of the time, absolute centering is the easiest way to
center in CSS; you should prefer it when possible.

[1]:
[http://codepen.io/shshaw/full/gEiDt](http://codepen.io/shshaw/full/gEiDt)

~~~
ChrisGaudreau
Would this technique work to center, say, an <img> tag with undeclared
dimensions inside of a div? Or do you have to jump through hoops?

~~~
pcwalton
No, if you don't have a defined height you will need to either use "display:
table", the table-cell technique, or flexbox. When I told the site that I had
a defined height, however, it still suggested the table-cell trick, which was
not the optimal solution because of the extra markup required.

In my experience, most of the time when I do want to center something
vertically, I have a defined height (which can be a percentage!), so absolute
centering is the solution of choice.

~~~
padolsey
With no defined height you can still use the `translate(-50%, -50%)` hack,
right? I'm kinda surprised it hasn't been mentioned in this thread at all; I
use it all the time.
[http://codepen.io/padolsey/pen/NqKzVG](http://codepen.io/padolsey/pen/NqKzVG)

------
sanbor
Another way to center flexible boxes is to use css transforms
[http://zerosixthree.se/vertical-align-anything-with-
just-3-l...](http://zerosixthree.se/vertical-align-anything-with-just-3-lines-
of-css/) CSS transforms have pretty good browser support
[http://caniuse.com/#feat=transforms2d](http://caniuse.com/#feat=transforms2d)

------
superasn
I really miss the HBox and VBox of Adobe Flex. They made aligning content so
damn easy (and it was responsive, no media queries either)

    
    
       <HBox height="100%" width="100%" horizontalAlign="center" verticalAlign="middle">
            <VBox>Col 1</VBox> 
            <VBox>Col 2</VBox>
            <VBox>Col 3</VBox>
        </HBox>

~~~
hawleyal
Ew, Adobe Flex

------
rivo
Unfortunately, this page does not give a solution to a long-standing centering
problem I've had: Given a single DIV of unknown width and height, how do I
center it in the middle of the screen (floating, i.e. fixed)? Note the "single
DIV" so no wrapping in additional container DIVs!

The only approximation I could find was this:

    
    
      .mydiv {
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%,-50%);
      }
    

This, however, looks horrible on most browsers as they either use hardware
acceleration (resulting in blurry output) or they drop pixels (e.g. single-
pixel lines) falling between the grid.

~~~
kowdermeister
Flexbox does it for you.
[http://codepen.io/kowdermeister/pen/mJbGdr](http://codepen.io/kowdermeister/pen/mJbGdr)

~~~
rivo
This also relies on a container DIV (".overlay"). So Flexbox doesn't help
here.

~~~
talmand
What exactly is your centered div centering to if there's no container div?
The .overlay div is the container, the .dialog div is centering itself as
defined by constraints of .overlay.

I'm failing to understand your expectations.

~~~
rivo
Let's say this is a modal dialog which is supposed to appear in the center of
the screen, fixed (but the size is unknown and may scale with its contents).
With any of the existing solutions, the HTML code for the dialog will always
be <div><div>...</div></div>, i.e. unnecessary DIVs due to the limitations of
CSS. Since it is supposed to float on top of everything else, it does not
matter what its container is. May as well be the <body> tag but applying
flexbox to that tag is likely not an option.

~~~
talmand
But the HTML you describe is required for the modal as you describe it. I
guess I'm assuming you want something to darken the body content behind the
modal, which is what the first div would be for.

Otherwise, if you don't need the darkening div behind the modal, you can
easily create a centered modal with the container being the body tag. Without
flexbox. Today.

Again, I don't understand your expectations.

------
damian2000
+1 more reason to avoid web development whenever possible. ;-)

------
amelius
My personal trick is to position the content absolutely at 50% (both left and
top), and then transform the content using a -50% translate in both
directions.

Works for dynamically sized content (and statically sized content as well,
obviously).

~~~
talmand
But then people whine about no support for a six-year old browser.

------
afarrell
This is the sort of thing that makes me conclude that the right way to teach
oneself html+CSS is to read about the basics and then just find 100
increasingly-difficult layouts to implement and grind through them.

------
yefim
Finally! I can't believe this is still such a big problem in CSS today.

------
SimeVidas
All the people who are still perplexed by this, have to admit that they
haven’t heard of or tried flexbox. It works beautifully (in conjunction with
Autoprefixer).

~~~
intruder
Heard of flexbox, it's nice but here's one thing I haven't been able to do
with it:

Center a bunch boxes in a row and have overflowing boxes show up on the next
row to the left or right. Doesn't work, it will center the next row as well.

I haven't found a non JS solution to this yet.

~~~
seekingcharlie
Not sure if I know exactly what you mean, but can you use :nth-child for the
nth box that shouldn't be centered?

------
lucaspottersky
oh man, that's a mad world we live in. look at that.

it's just sad to think that a browser can do so much stuff, yet it's unable to
provide a good layout system.

~~~
davesque
It's good at what it was originally designed for: flowable text documents.
And, honestly, it's come a long way since its early days. Used to be much
worse.

------
aps-sids
This site should give HTML and CSS separately, rather than giving inline CSS.

~~~
kijin
Maybe it's just me, but I find it much easier to understand exactly how a
proposed solution works when it uses inline CSS. If the HTML and CSS appear
separately, I have to look back and forth a lot to make sense of the whole.

Of course, when I actually implement it in my design, I prefer to separate my
CSS from my HTML.

I wish the solution was presented in both flavors, side by side.

------
neya
Wow, this IS a huge pain solver. I can't simply recall how many nights I've
been spending trying to fix the centering in CSS during my early days as a
frontend dev. Thank you,bookmarked!

------
CodeSheikh
This was not intended to be the entire solution but a great starting point
(more than that) for someone ( _cough_ backend devs _cough_ ) who has been
having issues with CSS centering.

------
picardo
This might need some updating. I did a quick run through and it recommended me
to use a table-cell for vertical centering. You might be able to do that more
easily with flexbox.

~~~
acdha
Depends on what you need for browser support – flexbox is supported in fewer
browser versions and requires using multiple rules because the spec changed
significantly before finalizing:

[http://caniuse.com/#feat=css-table](http://caniuse.com/#feat=css-table)

[http://caniuse.com/#feat=flexbox](http://caniuse.com/#feat=flexbox)

~~~
sondr3
Which is why you use something like AutoPrefixer to automagically generate the
needed browser prefixes and such, makes it a whole lot easier.

~~~
actionscripted
Which still doesn't cover older browsers just prefixes things appropriately
for those that support it.

~~~
kagamine
But for older browsers you can use the old specification too. This means
including the old specification before the new one in the CSS block; that will
provide a warning in the web-inspector. Then you will need a hack for <=IE8,
but I have had this working on a site since autumn 2013 (not a public site and
I therefore knew what browser versions had access). It is doable and it
provides a flexible layout.

here is a sample (btw, it's so long ago now, I included modernizer.js and
slectivizr.js but I have no idea if they were anything to do with this >_< and
why I keep referencing "flexie" I have no idea, the script, if it even was a
script isn't included on the page.... SO professional, such memory... ):

    
    
        	#box_content {
    	/* 1st draft flexbox required for IE8 layout using 'flexie' */
    		display: -moz-box; display:-webkit-box; display: -ms-box;
    	display: box;
    		-webkit-box-orient:horizontal; -moz-box-orient:horizontal; -ms-box-orient:horizontal;
    	box-orient: horizontal;
    		-webkit-box-align:center; -moz-box-align:center; -ms-box-align:center;
    	box-align:center;
    		-webkit-box-direction:normal; -moz-box-direction:normal; -ms-box-direction:normal;
    	box-direction:normal;
    		-webkit-box-pack:center; -moz-box-pack:center; -ms-box-pack:center;
    	box-pack:center;
    
    	/* 2013 flexbox! for FF3+, Safari3.2+, Chrome5+ */
    	display: flex; 
    		display: -moz-flexbox; display: -webkit-flexbox; display: -ms-flexbox;
    	flex-flow: row wrap;
    	justify-content: space-around;
    	padding-bottom: 1.5em;
    	}
    
    		.phonebox, .addressbox, .qrbox, .emailbox {
    			max-width: 250px; min-width: 200px;
    			height: 165px;
    			display: block;
    			border-radius: 20px;
    			color: #4d4d4d;
    			box-shadow: 2px 2px 9px #333;
    			border: 1px solid #A2E86C;
    			margin-top: 0.5em;/* req. for small screens */
    			/* More flexbox for older browsers (flexie.js)*/
    			-webkit-box-flex:0; -moz-box-flex:0;
    			box-flex:0;
    			-webkit-box-ordinal-group:1; -moz-box-ordinal-group:1; -ms-box-ordinal-group:1;
    			box-ordinal-group:1;
    		}

~~~
acdha
That assumes support exists at all (many people need IE8) or isn't broken in
some way which affects your design (Mobile WebKit is the worst offender here
but I've had to file bug reports for every major browser on this).

I want to just start using flex box everywhere, too, but we're just at the
point where that's becoming realistic. I won't fault anyone for waiting if
they have more representation from older browsers. The real progress lately
has been the push for Microsoft to get IE onto more of an evergreen update
schedule so we won't have to keep doing this once XP and IE8 are a bad memory.

------
crimsonalucard
This is why css is fundamentally broken. Centering should be a feature in
itself. I shouldn't be manipulating other attributes to achieve centering.

~~~
pcwalton
It _is_ a feature of CSS 2.1. See my reply to chubs above. CSS 2.1 10.6.4
requires that "margin: auto" on both sides of an absolutely-positioned element
mean "vertically center it".

~~~
crimsonalucard
You're saying that because they defined centering to occur when I mess with
margins that makes centering a feature? Technically yes...

I meant an explicit feature with it's own attribute.

~~~
pcwalton
Sure, and we have that now, with flexbox. "align-items" is the property you're
looking for.

I find it hard to fault the designers of CSS 2.1 for not being more complex
than it was at the time. CSS 2 was a huge advance over CSS 1, so much so that
a common feeling at the time was that CSS 2 had so many features no browser
vendor would ever implement it all. The authors of CSS 2.1 had to maintain a
delicate balance between giving authors the tools they needed and exploding
the complexity of the spec, and making vertical alignment fall out of "margin:
auto" was one of the ways they did just that.

------
explosion
I like that tool very much, but it would be nice to see the generated CSS
styles displayed separately from the HTML.

By this, I mean generating the following individually: 1) the HTML with a
class applied to a sample element to be centered 2) the separate CSS for that
particular class selector

This is just a little nitpick based on my preference for avoiding inline
styles; overall, nice work!

------
awalGarg
For everyone who thinks CSS is just a collection of hacks (rightly so) etc.,
you should try playing with GTK+3. It borrows a subset of CSS, has it's own
Flexy Grid model system etc. It will still be fair to call it a Work in
Progress but I think it's layout system is quite nice.

------
ocdtrekkie
The fact that this site exists is confirmation that all of my "bah humbug"
about using CSS over tables is pretty justified. And while CSS still renders
differently in every browser, I have yet to find a browser that can't render
tables consistently.

------
Kesty
And still the solution for centering a dynamic sized div is still using table-
cell.

------
michaelbuddy
If OP is the creator of the site, the width and height boxes are really small
on firefox desktop. I'm thinking at least show 3 characters wide, even four
would be smart.

------
btbuildem
It says something about the state of the art, that an issue so simple and
essential as this generates such a wealth of commentary. We're a long way from
home yet.

------
bifurcations
Would have been great to have this when I was first learning CSS. Problems
like this one are what made me so reluctant to touch frontend for a long time.

------
raverbashing
Now we all need is this as a SAAS (rest API) and create a jQuery plugin that
given the parameters returns the corresponding CSS

------
riquito
Time to learn flexbox

[http://flexboxin5.com/](http://flexboxin5.com/)

------
ddade
A _tutorial_ on how to center things? That's a pretty serious FAIL.

------
polygonplanet
Result display is too passive. But, radio buttons are so good design.

------
jan-hocevar
Scroll down after generating code, but other than that, great!

------
sukumargv
God Bless this guy!

------
jessekiddd
I was struggling with this yesterday

------
chad_strategic
Disrupt CSS

~~~
mmphosis
easy:

    
    
      <center>Disrupt</center>

------
devsquid
Flex plox

------
jrm2k6
Flexbox++

------
hachre
Great!!!

------
binwiederhier
Awesome!

------
MichaelCrawford
a bunch of non-breaking spaces on other side?

------
sengork
Note to self: the title of this article does not refer to aim-bots in Counter
Strike Source...

------
andrewliebchen
All mediums have constraints. Perhaps our designs should be better a working
within those constraints. Obviously, vertically centering in all situations is
something CSS doesn't do so well in some situations and just fine in others.
Know the situations in which it doesn't work and design another solution.

