32

其他人以前曾问过这个问题,但我从未见过足够的答案。<center>标签是否有有效的替代品?

我知道有margin: 0 auto;,但这需要设置宽度。还有align="center",但我相信那也是无效的代码。

有没有<center>这么简单有效的东西?在极少数情况下我仍然最终使用它,即使它已被弃用。就在今天,我最终使用 a<center>将需要以网页为中心的一个按钮居中。是的,我可以设置宽度并给出它margin: 0 auto,但要使单个元素居中需要做很多工作,而且它弄脏了我的代码,我为保持有序而感到自豪。<center>如果没有任何东西可以取代它,我真的不明白为什么首先被弃用。

谢谢!

4

9 回答 9

36

text-align: center是你应该使用的。事实上,理想的方式是这样的:

.center {
    text-align: center;
}
.center > div, .center > table /* insert any other block-level elements here */ {
    margin-left: auto;
    margin-right: auto;
}

显然,它并不像您希望的那么简单。

就个人而言,我只是使用:

.center {text-align: center;}
.tmid {margin: 0px auto;}

然后在需要的地方申请课程。

于 2012-07-13T20:43:50.317 回答
10

如果没有中心标签,要让元素居中并不容易。

为此,您需要做一个即使在 IE6 中也有效的解决方法:

您需要一个 div 包装器围绕您想要居中并使用的元素text-align:center; width:100%。在这个 div 中放置另一个 div 并设置margin为 auto 和text-align:left;

<div style="text-align:center; width:100%">
    <div style="margin:auto; text-align:left;">
        This Container is centered
    </div>
</div>

如果您只想使文本居中,您可以使用<p style="text-align:center;"></p>

这是核心。为了简化事情,您可以为此使用一个类(如 Kolink 所写):

CSS:

.center {
    text-align:center;
    width:100%;
}
.center:first-child { //doesn't work in IE 6
    margin:auto;
    text-align:left;
}

HTML:

<div class="center">
    <div>
        This Container is centered
    </div>
</div>
于 2012-07-13T20:53:06.703 回答
2

居中元素我用这个:

.middlr {
   display: block;
   margin: auto;
}

适用于每个/任何元素。为我工作。

于 2017-09-01T18:35:18.130 回答
1

不推荐使用的原因<center>是它不是语义标签,而是表示性的,我们应该避免在 HTML 中使用任何本质上不是语义的东西。

这与其他表示元素(如 等)已被弃用的原因<b>相同<i>,因为在 CSS 中有实现相同目的的方法。

于 2012-07-14T18:11:37.453 回答
1
.centered {
  margin-left: auto !important;
  margin-right: auto !important;
}
* > .centered {
  text-align: center !important;
  display: block;
}
于 2017-01-07T03:36:34.287 回答
1

更换中心标签:(应该同时做

将此样式用于父元素:

文本对齐:居中;

将此样式用于当前元素:

左边距:自动;边距右:自动;

于 2016-10-07T23:41:20.470 回答
0

这是 PHP-STORM 报价:使用这个:

<div style="text-align: center;"></div>
于 2015-09-23T19:22:26.547 回答
-1

text-align: center是等效的 CSS

于 2012-07-13T20:43:33.843 回答
-1

我在博客上找到了这个答案

<img src="bullswithhorns.jpg" alt="Michael with the bull" style="width:150px;height:200px;margin:0px auto;display:block">

资源

于 2017-09-15T22:06:35.483 回答