如何将<p>元素置于<div>容器中?

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中玩它

在此输入图像描述

  • 我没有投票给你,但如果文字长于一行,这将失败. (3认同)

Gor*_*ard 9

以使左/右定心,然后应用text-align: centerdivmargin: autop.

对于垂直定位,您应该确保了解这样做的不同方法,这是一个常见问题:div中元素的垂直对齐

  • margin:自动完成了这件事!谢谢。 (3认同)