Html 等同于 CSS 中的 <center> 标签?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7226056/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 10:19:55  来源:igfitidea点击:

Equivalent to <center> tag in CSS?

htmlcentercss

提问by laurent

I read that the <center>tag is deprecated, however I cannot find any real equivalent to it in CSS. text-alignworks for text but not other elements, and auto margins only work if you know the width of the container (so not a solution if you don't know the width in advance). So is there any real equivalent to this <center>tag?

我读到该<center>标签已被弃用,但是我在 CSS 中找不到任何真正的等价物。text-align适用于文本但不适用于其他元素,并且自动边距仅在您知道容器的宽度时才有效(如果您事先不知道宽度,则不是解决方案)。那么这个<center>标签有什么真正的等价物吗?

回答by Mike Crawford

text-alignshould work for other kinds of elements. Does this work?

text-align应该适用于其他类型的元素。这行得通吗?

.center { margin: auto; text-align: center; }

Edit Three Years Later :-D

三年后编辑 :-D

margin: auto;also makes the top and bottom margins "auto". That might not be what you want. Alternatively you could have something like:

margin: auto;还使顶部和底部边距“自动”。那可能不是您想要的。或者你可以有类似的东西:

.center {
  margin-left: auto;
  margin-right: auto;
  margin-top: 3px;
  margin-bottom: 3px;
  text-align: center;
  display: flex;
  justify-content: center;
}

This particular example will center the text horizontally while hardwiring the upper and lower margins to 3 pixels.

此特定示例将文本水平居中,同时将上下边距硬连线为 3 像素。

One can also say something like margin: 3px auto 3px auto;but I prefer spelling out the directions explicitly, as I can never quite remember what the order of the parameters are if I put them all on the one margin:setting.

人们也可以这样说,margin: 3px auto 3px auto;但我更喜欢明确说明方向,因为如果我将它们全部放在一个margin:设置中,我永远不会完全记住参数的顺序。

回答by Isaksen

There is a difference:

它们是有区别的:

<center>
  <span>Works</span>
</center>

<span style="margin: auto; text-align: center;"> And this is broken</span>

<div style="margin: auto; text-align: center;">But this works works</div>