替换<center>

Jac*_*Dev 25 html css deprecated

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

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

有没有那么简单的东西<center>有效?在极少数情况下我仍然最终使用它,即使它已被弃用.就在今天,我最终使用了一个<center>中心需要在网页上居中的一个按钮.是的,我可以设置宽度并给它margin: 0 auto,但是这对于单个元素的居中来说是很多工作,它会弄脏我的代码,我为自己保持有序而感到自豪.我真的不明白为什么一开始<center>就被弃用,如果什么也没有取而代之的话.

谢谢!

Nie*_*sol 28

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

.center {
    text-align: center;
}
.center > div, .center > table /* insert any other block-level elements here */ {
    margin-left: auto;
    margin-right: auto;
}
Run Code Online (Sandbox Code Playgroud)

显然,它并不像你希望的那么简单.

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

.center {text-align: center;}
.tmid {margin: 0px auto;}
Run Code Online (Sandbox Code Playgroud)

然后根据需要应用类.


Wol*_*Dev 7

没有中心标签的中心元素并不容易.

为此,您需要做一个甚至在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>
Run Code Online (Sandbox Code Playgroud)

如果您只想将文本居中,可以使用 <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;
}
Run Code Online (Sandbox Code Playgroud)

HTML:

<div class="center">
    <div>
        This Container is centered
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)