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?
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With