Html 将外部 div 居中,'text-align:center' 未按预期工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14460632/
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 05:08:51  来源:igfitidea点击:

Centering an outer div, 'text-align:center' not working as expected

csshtmlcentering

提问by a coder

I have a section of content in a div, and this is currently centered to the left. Fiddle.

我在一个 div 中有一段内容,目前它位于左侧居中。 小提琴。

I tried adding a container div like:

我尝试添加一个容器 div,如:

<div style='text-align:center; width:100px;'>[content]</div>

But no luck. Also tried this:

但没有运气。也试过这个:

<div style='margin: 0px auto; width:100px;'>[content]</div>

Content is still left aligned.

内容仍然左对齐。

This works, but I'd like to find the right way to do this with CSS:

这有效,但我想找到使用 CSS 执行此操作的正确方法:

<div style='width:100px;' align='center'>[content]</div>

Assistance appreciated. I'm tempted to do this with tables, but I need to break out of old habits!

帮助表示赞赏。我很想用桌子来做这件事,但我需要打破旧习惯!

采纳答案by Manuel Miranda

If you try to get the outer div centered respect to its parent (bodyin this case) you should set its lateral margins to auto:

如果您尝试使其外部 div 居中,body则应将其侧边距设置为 auto:

body div{
    margin: auto;
}

as you can see here

正如你在这里看到的

回答by Ilan Biala

The tool to center a div is actually margin: 0 auto;.

使 div 居中的工具实际上是margin: 0 auto;.

回答by DruDro

Wrap the content with another divinside "rounded-corners'.

用另一个div内部“圆角”包裹内容。

And write style="width: 100%; margin: 0 auto;"for this new div

style="width: 100%; margin: 0 auto;"为这个新 div写作