我想要我的 <p>
元素位于容器的中心 <div>
,就像完全居中一样——顶部、底部、左侧和右侧的边距均等地分隔空间。
我怎样才能做到这一点?
div {
width: 300px;
height: 100px;
}
p {
position: absolute;
top: auto;
}
<div>
<p>I want this paragraph to be at the center, but it's not.</p>
</div>
最佳答案
你不需要绝对定位 使用
p {
text-align: center;
line-height: 100px;
}
并随意调整...
如果文本超出宽度且超过一行
在这种情况下,您可以做的调整是在您的规则中包含显示属性,如下所示;
(我添加了背景以便更好地查看示例)
div
{
width:300px;
height:100px;
display: table;
background:#ccddcc;
}
p {
text-align:center;
vertical-align: middle;
display: table-cell;
}
在这个 JBin 中使用它
关于html - 如何将 <p> 元素置于 <div> 容器的中心?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15121343/