【发布时间】:2020-10-11 15:18:39
【问题描述】:
我正在 Codecademy 中学习 CSS。我已经上过他们的 HTML 课程,所以我知道center 标签。但是,现在他们引入了 CSS 边距属性。他们还介绍了margin: 0 auto; 属性。据我所知,两者都做同样的事情。那么有什么区别吗?我什么时候使用每一个,还是没关系?提前致谢!
【问题讨论】:
-
这个问题已经解决了Here是链接
我正在 Codecademy 中学习 CSS。我已经上过他们的 HTML 课程,所以我知道center 标签。但是,现在他们引入了 CSS 边距属性。他们还介绍了margin: 0 auto; 属性。据我所知,两者都做同样的事情。那么有什么区别吗?我什么时候使用每一个,还是没关系?提前致谢!
【问题讨论】:
<center> 是一个已弃用的标签。你应该避免使用它。 HTML5 不支持此标记。 CSS 属性用于设置元素的对齐方式,而不是 HTML5 中的 center 标签。 <center> 的等效标记可以被认为是 -
.center { margin: 0 auto; text-align: center; }
<center> 被贬值的主要原因是它定义了其内容的呈现方式,而不是内容本身。根据w3.org -
CENTER 元素完全等同于指定 DIV 元素 对齐属性设置为“中心”。中心元素是 已弃用。
那么有什么区别吗?我什么时候使用它们,或者没关系?
上面的代码sn-p和<center>可以认为是等价的。只是使用margin: 0 auto; 并不总是被认为是相同的。请参阅下面的示例 -
<!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>
要考虑的另一点是<center> 标签是一个块级元素,这意味着它可以包含其他块级和内联元素并将它们居中。考虑下面的例子 -
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>
【讨论】:
margin: 0 auto 与margin: auto 0 不同
margin: 0 auto。现在编辑它以避免混淆
正如 W3Schools wiki 描述的here,HTML5 不支持<center></center> 标签,尽管由于向后兼容,浏览器仍可以使用它。最好的办法是使用margin: 0 auto 属性。
【讨论】: