tehyoyo — 2012-03-17T15:56:35-04:00 — #1
I've seen people center various elements (mainly divs) using two syntaxes:
Which way is the better way?
ryanreese — 2012-03-17T16:19:07-04:00 — #2
It honestly doesn't matter. In the specs, it's specified that if "auto" is the value for top/bottom margin it automatically becomes 0. So it's just easier to type margin:0 auto;.
When you say margin:auto auto;, that can be shortened to margin:auto; (one value for margin specifies that value for all 4. top, right, bottom, left)
tehyoyo — 2012-03-17T16:47:21-04:00 — #3
So will that vertically center the element as well? (as it has margins for all 4?)
ryanreese — 2012-03-17T17:09:05-04:00 — #4
If only it were that simple :). Vertical centering with CSS isn't as easy as setting vertical margins. There are a variety of other ways to do it however. Such as display:inline-block, display:table-cell (and the actual <table> HTML), and some mix of position:absolute trickery.
The display:table-cell isn't usable much right now due to IE7 still being here (though if you don't care about that, by all means use it). I prefer to use display:inline-block (and advocate it over table-cell for now, until IE7 dies).
tehyoyo — 2012-03-19T15:50:26-04:00 — #5
Well logically, if we have a defined height auto margins should be the way to go?
Is it because it's usually a bad idea to have a defined height?
ryanreese — 2012-03-19T18:41:54-04:00 — #6
Vertical auto margins are automatically calculated to 0 when set. You simply can't center vertically using that method. Logically it should work because of it working with width, but it doesn't work like that :).
It's bad to have a defined height (in most cases, aka content) but that's not why you shouldn't resort to auto margins for vertical centering . They just don't work!
tehyoyo — 2012-03-19T20:46:48-04:00 — #7
Gotcha. I can't foresee many times when I would have to vertically center...maybe in table cells, but it seems to be done automatically anyways (at least for TH tags).