I am learning CSS in Codecademy. I had already taken their HTML course so I knew about the center
tag. However, now they introduced the CSS margin property. They also introduced the margin: 0 auto;
property. From my knowledge, both do exactly the same thing. So is there any differences and when do I use each one or does it not matter? Thank You In Advance!
<center>
is an depreciated tag. You should avoid using it. This tag is not supported in HTML5. CSS property is used to set the align of the element instead of the center
tag in HTML5. An equivalent tag to <center>
can be considered to be -
.center { margin: 0 auto; text-align: center; }
The main reason why <center>
was depreciated was because it defines the presentation of its contents and not the contents itself. According to w3.org -
The CENTER element is exactly equivalent to specifying the DIV element with the align attribute set to "center". The CENTER element is deprecated.
So is there any differences and when do I use each one or does it not matter?
The above code snippet and <center>
can be considered equivalent. Just using margin: 0 auto;
can't always be considered the same though. See the below example -
<!DOCTYPE html>
<html>
<body>
<center>
<div>This is a div inside center</div>
</center>
<br>
<div>This is a div without any styling.</div>
<br>
<div style="margin: 0 auto;">This is a div with "margin: auto 0px;".Text not centered, doesn't work.</div>
<br>
<div style="margin: 0 auto;text-align:center">This is a div with "margin: auto 0px;".Text centered, works !</div>
</body>
</html>
Another point to consider is that The <center>
tag is a block-level element, which means it can contain other block-level and inline elements and center them. Consider below example -
p {
width: 200px;
display: block;
}
<!DOCTYPE html>
<html>
<body>
<!--p has a width of 200px given through css-->
<center>
<p>centers the element to page center</p>
</center>
<center>
<div style="margin:0 auto;text-align:center;">
<p>This one doesn't work here same as center tag </p>
</div>
<div>
<p style="margin:0 auto;text-align:center;">This one does</p>
</div>
</body>
</html>