Joh*_*nsy 35 html css text centering
我希望我的<p>元素位于容器的中心<div>,就像完美居中一样 - 顶部,底部,左侧和右侧边距平均分割空间.
我怎样才能做到这一点?
div {
width: 300px;
height: 100px;
}
p {
position: absolute;
top: auto;
}Run Code Online (Sandbox Code Playgroud)
<div>
<p>I want this paragraph to be at the center, but it's not.</p>
</div>Run Code Online (Sandbox Code Playgroud)
Fic*_*ico 52
你不需要绝对定位使用
p {
text-align: center;
line-height: 100px;
}
Run Code Online (Sandbox Code Playgroud)
并随意调整......
如果文本超出宽度并且超过一行
在这种情况下,您可以执行的调整是在规则中包含display属性,如下所示;
(我添加了一个背景,以便更好地查看示例)
div
{
width:300px;
height:100px;
display: table;
background:#ccddcc;
}
p {
text-align:center;
vertical-align: middle;
display: table-cell;
}
Run Code Online (Sandbox Code Playgroud)
在这个JBin中玩它

以使左/右定心,然后应用text-align: center到div和margin: auto到p.
对于垂直定位,您应该确保了解这样做的不同方法,这是一个常见问题:div中元素的垂直对齐