Karim
Karim

Reputation: 6283

What is the difference between using `text-align:center` and `margin: 0 auto` to center an element in CSS?

I have read in a lot of places to center elements (a div for example) using margin:0 auto.
but why not use align:center? I think it seems more natural to use the later.

Also, can we use margin approach to set vertical alignment too?

Upvotes: 15

Views: 22153

Answers (3)

Pointy
Pointy

Reputation: 413846

First, there is no "align: center". What you're thinking of is "text-align: center", and that detail — the prefix "text-" — is a hint as to what the problem is. The "text-align" property is for inline elements being laid out in blocks. When you're trying to center a block-level element in some content, an inline layout style does not make sense.

The (now deprecated) align attribute on elements is not a CSS thing; it's a throwback to the days of yesteryear.

Now, as to vertical alignment, sadly the answer is "no," at least in practical terms. The trick with "margin: auto" won't work. Vertical alignment with nothing but CSS is challenging, to put it mildly. There are many different situations and techniques to use. Here's an interesting (if a little old) page on the subject: http://www.student.oulu.fi/~laurirai/www/css/middle/

edit from the future — Anybody trying to do vertical centering should be keeping an eye on the availability of flexbox layout.

Upvotes: 16

Sarfraz
Sarfraz

Reputation: 382806

text-align=center used to align the content (text for example) to center, however margin: auto is used to align the element itself to center.

In older browsers however (IE), you could align elements to center using text-align:center.

But I suspect you meant align=center like in below example:

<p align="center">
 .......
</p>

<h1 align="center">
 .......
</h1>

However, not all elements have align="center", you will have to use margin:0 auto to align for them.

So,

If you want to align content of an element, you should do:

<p style="text-align:center">
 .......
</p>

If you want to align element itself, you should do:

<div style="margin:0 auto;">
 .......
</div>

<p style="margin:0 auto;">
 .......
</p>

Upvotes: 7

Philippe Leybaert
Philippe Leybaert

Reputation: 171864

text-align: center will center the contents of the container, while margin: auto will center the container itself.

You should be careful with margin:auto because it is not supported in IE6. In IE6, you should set text-align:center on the outer container, and reset the CSS for the container itself to text-align:left.

Upvotes: 28

Related Questions