繁体   English   中英

不能使用text-align:center来居中div

[英]Cannot center inner div with text-align: center

我以前认为下面的两个代码块都会正确地居中div(当然,旧版浏览器存在一些问题)。 第一种方法使用text-align: center而第二种方法使用auto左右边距。 但是,下面的第一个代码块并不像我期望的那样使内部div居中。 有什么想法吗?

 <div style="text-align: center; background-color: red;"> <div style="border: solid 1px black; width: 100px; height: 100px; background-color: blue">Not working</div> </div> 

以下代码确实使div居中:

 <div style="background-color: red;"> <div style="border: solid 1px black; width: 100px; height: 100px; background-color: blue; margin-left: auto; margin-right: auto">Works</div> </div> 

这是我的JSFiddle

它是一个块级元素,它的位置不受text-align属性的影响。 如果将其设置为display-inline ,它将起作用。

<div style="text-align: center; background-color: red;">
    <div style="border: solid 1px black; width: 100px; height: 100px; background-color: blue; display: inline-block;">It will work now</div>
</div>

中心的div有margin-left: automargin-right: auto ,不工作的div缺少任何边距。

看这个DEMO

在顶部框中,我添加了: margin: 0 auto ,这是简写: margin-top: 0; margin-bottom: 0; margin-left: auto; margin-right: auto; margin-top: 0; margin-bottom: 0; margin-left: auto; margin-right: auto;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM