Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 580
Karim Avatar asked Mar 06 '10 13:03

Karim


People also ask

Why is margin 0 auto?

0 is for top-bottom and auto for left-right. It means that left and right margin will take auto margin according to the width of the element and the width of the container. Generally if you want to put any element at center position then margin:auto works perfectly.

What is needed for margin 0 Auto to work?

The element must be block-level, e.g. display: block or display: table. The element must not float. The element must not have a fixed or absolute position.

How do you align text to the center in CSS?

To center text in CSS, use the text-align property and define it with the value 'center. ' You can use this technique inside block elements, such as divs. You can also center text in HTML, which is useful if you only want to center individual elements on the page on a case-by-case basis.


1 Answers

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.

like image 87
Philippe Leybaert Avatar answered Nov 10 '22 00:11

Philippe Leybaert