如何使 <p> 标签中的文本垂直居中?

How can I center the text within a <p> tag vertically?

我正在尝试将

标签置于其容器的中心,虽然我已经能够(使用 top/translateY)将标签本身居中,但文本的中心实际上并不是

标签内容的中心,如此处所示(红线是标签的真正中间):

如何让

标签中的文本也居中?

你可以尝试点赞:

p.myclass {
    font: bold 12px "Helvetica Neue", Helvetica, Arial, sans-serif;
    line-height: 10px;
    height:30px;
    margin: 0px;
    display: table-cell;
    vertical-align: middle;
    padding: 10px;
    bordeR: 1px solid #f00;
}
<p class="myclass">test</p>

你等中间的文字。视觉上看起来少了,因为你使用的是小写字母,而文本的高度是由大写字母计算的。

HTML:

<div>
  <p>Hello World</p>
</div>

CSS:

div {
  width: 300px;
  height: 100px;
  background: red;
}

p {
  text-align: center;
  line-height: 100px;
}

演示:https://jsfiddle.net/vv3uy7vy/

<p>Hi </p>

p{border:1px solid red; height:30px; line-height:30px;}

将容器(这里是"p"标签)的"height"赋给line-height将使内容垂直居中

要将 <p> 标签置于其容器的中心,请尝试使用 table 的 属性。 例如,您必须将父容器的 属性 设置为 display:table,然后将其子容器 属性 设置为 display: table-cell;vertical-align: middle;

Check this fiddle here

你的样本 HTML 应该是这样的,

<div class="parent">
    <div class="child">
        <p>...... Your Text goes here .....</p>
    </div>
</div>

相对的CSS应该是这样的,

.parent {
    width: 300px;
    height: 200px;
    background: blue;
    padding: 30px;
    display: table;
}

.child {
    display: table-cell;
    vertical-align: middle;
}

p {
    display: block;
    text-align: center;
    color: #FFFFFF;
    margin: 0px;
}

For your reference check this out