Centering

I’ve seen people center various elements (mainly divs) using two syntaxes:


margin:0 auto;

and

margin:auto auto;

Which way is the better way?

~TehYoyo

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) :slight_smile:

So will that vertically center the element as well? (as it has margins for all 4?)

~TehYoyo

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).

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?

~TehYoyo

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! :stuck_out_tongue:

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).

~TehYoyo