
The complete guide to centering a div - SteveP1961
http://www.tipue.com/blog/center-a-div/
======
crazygringo
Whenever anybody says that CSS is easy, or "of course you can do that with
CSS", or even hints that CSS is somehow well-designed...

...the only thing I really need to say, is that every couple months, on Hacker
News, where a lot of really smart people hang out, a new top-voted story comes
up about _how to center a div_. With tons of comments and discussion too. And
it's not even a joke.

What more is there to say?

~~~
adwf
Next week: The complete guide to sticky footers!

It's unbelievable just how annoying CSS can be for seemingly simple things.

~~~
sopooneo
I may be using words incorrectly, and I'm not positive you can even make the
distinction, and I am happy to stand corrected, but it always seemed to me
that CSS was fine for _style_ , but terrible for _layout_.

So I think I'm agreeing with you.

~~~
jebblue
Right, to me plain HTML tables are great for overall master page layout yet it
seems everything I've read and the few web geniuses I've met will deride using
them over CSS.

~~~
statictype
Generally I agree that too many people have a fetish about avoiding tables
when it's clearly the right tool for the job. But I've definitely been bitten
by using them. Table layouts don't play well with other CSS properties.

~~~
buttsex
If you are using HTML tables for layout then you definitely aren't using the
right tool for the job. If it isn't tabular information then it doesn't belong
in a table.

~~~
ahallock
You can easily get around that by using `display: table` and `display: table-
cell` So you have your semantic HTML elements, if you're into that sort of
thing, and flexible layout options, like `vertical-align: middle`.

------
TheZenPsycho
Of course, CSS was a compromise between old guard semantic "purists" (who
envisioned an HTML document as being pure text with structural meaning
semantically applied to the content via tags, with the browser in full control
of presentation) and designers, who wanted control over look and layout (the
fools!). And so, CSS was created, and designers could have their silly colours
and fonts. Any layout or typographic abilities were added as a neglected and
poorly considered afterthought.

Designers being what they are, worked out systems like tables, and the hacks
in the link to get what they want out of CSS anyway. (but why would you want
to centre anything? that's stupid! the original designers of CSS grumble)

meanwhile, far superior systems, such as "Constraints Based CSS" were
proposed, and ultimately rejected because it's stupid and irresponsible to
want to control the layout of a webpage!

Now it's 2014 and we have flex box as a patch over. Constraints based css
would have been much better, and that's what you get in Cocoa Auto-layout now,

but oh well. let's copy java and flash. what difference does it make?

[http://www.cs.washington.edu/research/constraints/web/ccss-u...](http://www.cs.washington.edu/research/constraints/web/ccss-
uwtr.pdf)

------
lpolovets
I don't know anything about the history of CSS's design, but I'm perpetually
amazed that positioning (and specifically centering) requires so much CSS
magic. I would think CSS positioning would be a one-liner, but instead it's a
collection of context-dependent, browser-dependent recipes. I wonder if
there's a good reason for the madness, or if it's just poor design. (FWIW, I'm
a backend engineer and have only dabbled with front-end code.)

~~~
Tloewald
The thing that boggles my mind is that we're over ten years and three major
versions in and we can't center stuff reliably or conveniently, images won't
scale up to fit (only down...), multi-column text is barely implemented and
Google is ripping it out, the box model is borked by default, it's non-trivial
to determine the layering of UI elements, and so on.

It's amazing that we get solutions for things that no-one really needs
(animated 3d transitions...) while bread and butter stuff still requires
rocket science. Back in 2005 I used to joke that 90% of the world's Javascript
was just doing button rollovers (probably a conservative estimate) — well, CSS
eventually fixed that, kind of — now Javascript is mostly doing similarly
idiotic stuff like handling resizing, making things that aren't lists
impersonate lists because multi-selects are borked, centering stuff, and
trying to reliably hook up event handlers.

All of which were solved problems before the web was born.

~~~
GhotiFish
Good thing we are practically putting all our eggs in this basket.

HTML and CSS will be our document structure, and javascript will describe how
the document behaves. Truly a universal standard for the ages.

Humans are dumb.

~~~
Tloewald
Javascript gets a lot of shit, but really the biggest WTFs are HTML and
especially CSS. Javascript at least has Crockford. No-one really has a handle
on how to deal with CSS -- it's a wall-to-wall disaster.

~~~
cheapsteak
Preprocessing languages like SASS help a little. They don't really fix the
ugly parts, but do help shove them under the bed a little more

------
clhodapp
The Web Styling Challenge: you and another person are going to make a web
site. You are doing the HTML, while the other person does the CSS (you can
discuss it and swap jobs if you want). You can talk as much as you want ahead
of time, but the only record you can keep is a table that maps CSS selectors
to a description of what you'll be using them for. You are then split up and
do your individual tasks. When you're finished, you will be judged on how
broken the results of combining your pages with the other person's stylesheets
are. I think just imagining how this game would go makes it pretty clear that
CSS is lousy at separating the concerns of style and layout.

------
shawnz
> Centering a div Within a div, Horizontally and Vertically

The code in this section is incorrect. "margin: auto" does nothing in the
vertical direction. If you set the height of the outer div to something more
than 160 px, you will see that the inner div is not centered.

~~~
jessedhillon
Came here to say the same thing. Not sure the rest of the article is worth
reading if the author doesn't know CSS well enough that a) they don't know _a
priori_ that this is wrong, and b) manages to convince themselves it's true
using Codepen

Here's the Codepen that shows it with a larger outer div,

[http://codepen.io/jessedhillon/pen/CDqEe](http://codepen.io/jessedhillon/pen/CDqEe)

~~~
SteveP1961
No, it doesn't work with a fixed height. I didn't claim it did, of course. In
a responsive world fixed heights in a container are somewhat irrelevant, but
I'll amend the article.

~~~
jessedhillon
What? It doesn't work _at all_ \-- without a fixed height, the height of
#outer would be determined by summing the heights of its statically/relatively
positioned children.

If there were multiple children of #outer, #inner would _still_ not be
centered vertically. This only works for some trivial definition of vertical
centering, when what you really mean is that a single block child will occupy
the vertical center position of its block parent, provided the parent's height
is not specified. Which is the most obvious of statements in CSS.

~~~
SteveP1961
It works in a container with no fixed height. Perhaps it doesn't work for your
particular requirements, but it does work.

~~~
kaichanvong
The the element is merely sitting on the line-height and not being positioned.
So no, I think you are incorrect on that one. It is a nice bit of work
otherwise.

~~~
SteveP1961
Thanks, but isn't that semantics? :-)

~~~
jessedhillon
The height of the outer element is determined by the height of the children,
plus padding. Since you have only one child, then the outer element is as tall
as that one child, plus padding. Ergo, _assuming symmetrical vertical padding_
, the inner element will _by definition_ be centered.

It would be as if I wrote a tutorial on how to make one element fill the
entire viewport, and one of my methods was "put all your content in the <body>
tag" and I said that was a way to fill the viewport. That is the trivial case,
it's a degenerate solution!

~~~
SteveP1961
> it's a degenerate solution!

Well, there you go. :-)

------
lisper
I wrote this five years ago. I'm somewhat dismayed at how relevant it still is
today:

[http://www.flownet.com/ron/css-rant.html](http://www.flownet.com/ron/css-
rant.html)

~~~
leephillips
That article, and especially the second followup, are brilliant. Well argued,
sharply written.

~~~
lisper
Thank you!

------
DigitalSea
My utmost favourite technique for centering unknown width and height
DIV's/elements perfectly center in the page is using 2dtransforms. I've
created a Codepen here that shows off the technique, it's simple and well
supported IE9+:
[http://codepen.io/Figurated/pen/zcypx](http://codepen.io/Figurated/pen/zcypx)
— if you don't need to support IE8 any more, it's a perfect solution.

~~~
hesslau_
My favourite technique: position absolute and top: 0 bottom: 0 left: 0 right:
0

also doesn't require a fixed width
[http://codepen.io/anon/pen/vsliJ](http://codepen.io/anon/pen/vsliJ)

~~~
olivier1664
Your technique is less good (on IE11) when you resize the width of the
browser. The text finish outside the div, while DigitalSea's solution works
well.

------
maj0rhn
This is a pointless post. Use the TABLE tag. Yes, it will violate the purity
of CSS, but you can trust it, and it will make your day better because it will
free you angst and from extensive cross-browser testing. Simple is better than
complex. Straightforward is better than arcane.

~~~
peter_l_downs
As igvadaimon wrote below, there's no need for a <table> tag. Instead of:

    
    
        <table>
          <tr>
            <td> my div </td>
          </tr>
        </table>
    

you can do

    
    
        <div style="display: table;">
          <div style="display: table-cell;
                      vertical-align: middle;"> my div </div>
        </div>
    

The inline styling is just for illustrative purposes, of course.

~~~
maj0rhn
I'll admit that the table-cell approach is nice -- thank you. But how curious
that the article, which purports to be an in-depth examination, doesn't
mention it. And how curious that the table-cell approach has not turned up in
the numerous times I've gone looking on-line for a robust, pure CSS solution.
I've long harbored suspicions that many CSS gurus are too quick to adopt
complex solutions.

~~~
masklinn
It doesn't mention flexbox[0] either. It's not an in-depth examination, it's
blogspam. There are better[1] years-old[2] resources which are no more
incomplete.

[0] [http://philipwalton.github.io/solved-by-
flexbox/demos/vertic...](http://philipwalton.github.io/solved-by-
flexbox/demos/vertical-centering/)

[1] [http://css-tricks.com/centering-in-the-unknown/](http://css-
tricks.com/centering-in-the-unknown/)

[2] [http://gtwebdev.com/workshop/vcenter/vcenter-inline-
css.php](http://gtwebdev.com/workshop/vcenter/vcenter-inline-css.php)

------
hawkharris
What about cases in which developer wants to vertically center a div, but he
or she doesn't want to specify a height property?

~~~
Mandatum
Then unfortunately you have to calculate it with JS if it varies. Vertically
centering divs has always been a gigantic pain-in-the-ass. If anyone has a
better idea for doing this without JS, please let me know. Once CSS implements
variable-based elements (ie #div.height) then we'll have a lot more control.

~~~
markdown
> If anyone has a better idea for doing this without JS, please let me know.

Flexbox, with optional fallback to JS for IE 8 and 9. That said, vertical
centering is almost always a nice-to-have rather than a must-have so
personally I wouldn't even use a fallback.

[http://philipwalton.github.io/solved-by-
flexbox/demos/vertic...](http://philipwalton.github.io/solved-by-
flexbox/demos/vertical-centering/)

[http://caniuse.com/flexbox](http://caniuse.com/flexbox)

------
STRML
This is my favorite vertical centering method [1] and combined with the
table/table-cell method, it allows me to avoid using JS for layout about 95%
of the time. It's not very well-known and even though I've used CSS for well
over a decade, I have no idea why it works.

The real trick is realizing that `margin:auto` actually _does_ do something,
so long as you set a fixed width/height and position: absolute with dimensions
set to 0. But for the life of me, I don't understand why that happens to trick
the box model into working properly. But this technique is _fantastic_ and
really helps out when table/table-cell interacts badly with your styles, or
you need to support older browsers.

I would be very happy if someone in the know could explain why this technique
works.

[1] [http://codepen.io/anon/pen/whHIL](http://codepen.io/anon/pen/whHIL)

------
bliker
I was wondering why the demo is not working for me. it really took me a while
to realize that it is actually a button.

~~~
10feet
Obviously you can't show off css in the same browser window as your text, that
would be insane. No, you have to load up a completely different website, that
makes much more sense.

~~~
SteveP1961
CodePen shows live code that can be edited and played around with. It does
make sense.

~~~
10feet
No, it does not. It is good to be able to play around with the code, but to
require someone to see the code working it is overkill.

------
joshfraser
<center><div>I'm centered!</div></center>

~~~
_mtr
DRY, though, right? Changing one set of CSS rules is better than hunting down
20 <center> elements when requirements change. Not to mention <center> is
deprecated.

~~~
dangrossman
When requirements change —

    
    
        center { text-align: left }

------
addedlovely
A few additions. If you know the width and height of the element, centering
horizontally & vertically can be achieved with one <div> like so:

.center-div { height:100px; width: 100px; position:absolute; top:50%;
left:50%; margin: -50px 0 0 -50px; }

This can be modified for the 'centering at the bottom of the page' example,
but with more efficient code.

More challenging is centering the unknown: [http://css-tricks.com/centering-
in-the-unknown/](http://css-tricks.com/centering-in-the-unknown/)

------
null_ptr
Is it me or is the content of this page annoyingly off-centered?

------
mrmartineau
For an in-depth look at all the different options for centering an element,
have a look at Stephen Shaw's research on Codepen:
[http://codepen.io/shshaw/full/gEiDt](http://codepen.io/shshaw/full/gEiDt)

------
potch
This article is not actually correct. There are really 2 or three techniques
for centering a block level element. The post repeats these techniques for
multiple scenarios, and is wrong about the first vertical centering technique.

------
burgerguyg
Maybe I'm thick. The article is dated February 2014, it says flexbox
"currently lacks browser support, mainly in IE (version 10 has partial support
and full support won't arrive until version 11). Chrome, Safari and Firefox
have support but with browser vendor prefixes."

IE11 came out in preview in June 2013, released officially in November 2013,
and at least IE and Mozilla are currently supporting it unprefixed (though
Mozilla's multi-line flexbox fails last time I checked). This article is over
3 months out of date, if not more, but being presented as new and current.

------
mcot2
I've been using Flexbox for a while now. Unless you need to support older IE
than it is quite usable. The one problem is the older syntax for IE10 but it
is fixed in IE11 and going forward.

------
boyaka
I've been working on this form with php [1]. Only positioning I've tried so
far is using tables. Focusing on functionality for now, figure I can just wait
til it works to make it look pretty. Haven't really worked to understand CSS
since I was in middle school in the late 90s.

[1] [http://i.imgur.com/eRbSdbT.png](http://i.imgur.com/eRbSdbT.png)

------
JazCE
Shame that demo's take you out of the site.

------
angersock
Despite a wonderful article, I cannot help but notice that it is 2014 and we
still need multiple ways of centering a div. :(

~~~
tagliala
...and the one that really works (variable height and width) uses `display:
table` :(

------
trajektorijus
Best centering (vert. and hor.) solution ever: .outer { position: relative; }
.inner { position: absolute; top: 50%; left: 50%; transform: translate(-50%,
-50%); }

<div class="outer"> <div class="inner"></div> </div>

This way you don't need to know the width or height of inner element...

------
apu
The critical piece I'm always missing is how to center a div vertically if you
don't know its height?

~~~
igvadaimon
Well, I'd use display:table-cell with vertical-align:middle.

~~~
platypii
Doesn't work without the parent having a defined height.

------
CmonDev
All the problems with HTML and CSS in one title. All hail the "modern GUI
development"!

------
DavidSJ
From six years ago, during which it would seem CSS has gotten no better:
[http://beradrian.files.wordpress.com/2008/01/breakdown.png](http://beradrian.files.wordpress.com/2008/01/breakdown.png)

------
tkirchner
There is really not much more to say...

...maybe that the reason for all of this is that the CSS API (box model ...,
box properties ...) is too complex and as a result browser implementations
tend to f __* it up easily.

------
msie
Is there a framework that allows one to avoid most of CSS and just use js?

~~~
sehr
Even if there was, if something went wrong you'd just have more shit to sift
through.

------
EGreg
After IE6, we can just center a div using inline-block, can't we?

The outer element can have display: table-cell and the inner element would
have vertical-align: middle and display: inline-block.

------
rcruzeiro
One day someone will have to come up with a convincing explanation on why the
hell is margin: auto; unable to vertically center an element if the outer
element has a defined height.

------
sideproject
anyone miss <center> tag? :)

~~~
sfaruque
I'm curious, why did they remove the <center> tag? What was wrong with it?

------
kyberias
Is this article intentionally ironic with a column of text that isn't centered
as the header is?

------
whalesalad
The irony here is that the content of this post is not centered.

------
level09
nice list, would be nicer to have a more detailed definition of "modern
browsers" , like browser types/versions that support each method.

~~~
SteveP1961
Noted. Thanks.

------
runn1ng
....

    
    
        <center>
    

will not work?

~~~
_mtr
> This feature has been removed from the Web. Though some browsers may still
> support it, it is in the process of being dropped. Do not use it in old or
> new projects. Pages or Web apps using it may break at any time.

[https://developer.mozilla.org/en-
US/docs/Web/HTML/Element/ce...](https://developer.mozilla.org/en-
US/docs/Web/HTML/Element/center)

~~~
Zarel
It also won't work because <center> controls text alignment and will have no
effect on the alignment of a div (it will center its contents, though) (also
this isn't entirely true, centering text will also center divs in IE6 and
earlier).

------
greatsuccess
The fact that centering a div requires a complete guide is tragicomically sad
and a condemnation of our industry.

