我的div无法居中HTML CSS

3

我的代码

.nav_bar {
 position: absolute;
 top: 0;
 width: 800px;
 height: 23px;
 display: inline-block;
 text-align: center;
 background-color: #0090bc;
 border-bottom-left-radius: 12px;
 border-bottom-right-radius: 12px;
 border: 2px solid #004D6F;
 -webkit-box-shadow: inset 2px 2px 0px rgba(255, 255, 255, 0.7), inset -2px -2px 0px rgba(0, 0, 0, 0.7);
 box-shadow: inset 2px 2px 0px rgba(255, 255, 255, 0.7), inset -2px -2px 0px rgba(0, 0, 0, 0.4);
 padding: 10px;
 font-family: arial;
 color: white;
}
<center>
 <div class="nav_bar">
  <center><font size="5"><span class="shadow"><b>Text</b></span></font></center>
 </div>
</center>

由于某种原因,'.nav_bar' div不会居中!以下是输出结果!我已经添加了center标签以查看是否会居中,但它不会。请有人帮助我。

输出: enter image description here


2
你使用了position:absolute。这意味着你正在显式地定位它。它不会自动居中。 - Lance
3
“center”和“font”是过时的标签,不应再使用。请注意更新代码。 - Paulie_D
1
@Lance 你实际上可以使用绝对定位居中...但是这是一种不好的做法:). 例:position: absolute; left: 50%; margin-left: -400px; width: 800px; - zozo
3个回答

7

删除

position:absolute;
top: 0;

添加

margin: 0 auto;

这里有一个 jsfiddle: https://jsfiddle.net/efhu4h4h/

请注意,我将宽度更改为100px,以便适应窗口。


2

如果您想保持 position: absolute,您可以将以下样式添加到 .nav_bar 来使其居中:

left: 50%;
-webkit-transform: translateX(-50%);
-moz-transform: translateX(-50%);
transform: translateX(-50%);

-1
在你的 CSS 类中添加 align:center。
align:center ;

它对你有效


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接