我有一个div设置显示:块(90px高和宽),我有一些文本在里面。

我需要文本在中心垂直和水平对齐。

我已经尝试了text-align:center,但它不做垂直居中部分,所以我尝试了vertical-align:middle,但它不起作用。

什么好主意吗?


当前回答

这招对我很管用:

.center-stuff{
    text-align: center;
    vertical-align: middle;
    line-height: 230px; /* This should be the div height */
}

其他回答

<!DOCTYPE html>
<html>
  <head>
    <style>
      .maindiv {
        height: 450px;
        background: #f8f8f8;
        display: -webkit-flex;
        align-items: center;
        justify-content: center;
      }
      p {
        font-size: 24px;
      }
    </style>
  </head>

  <body>
    <div class="maindiv">
      <h1>Title</h1>
    </div>
  </body>
</html>

这适用于我(测试OK!):

HTML:

<div class="mydiv">
    <p>Item to be centered!</p>
</div>

CSS:

.mydiv {
    height: 100%; /* Or other */
    position: relative;
}

.mydiv p {
    margin: 0;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-right: -50%;
    transform: translate(-50%, -50%); /* To compensate own width and height */
}

您可以选择50%以外的其他值。例如,25%到父母的25%的中心。

试试下面的例子。我为每个类别添加了示例:水平和垂直

<!DOCTYPE html>
<html>
    <head>
        <style>
            #horizontal
            {
                text-align: center;
            }
            #vertical
            {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translateX(-50%) translateY(-50%);
            }
         </style>
    </head>
    <body>
         <div id ="horizontal">Center horizontal text</div>
         <div id ="vertical">Center vertical text</div>
    </body>
</html> 

这应该是正确答案。最干净最简单:

.element {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

这是非常简单的代码,为我工作!它只有一行,你的文本将水平居中。

.center-horizontally{
  justify-content: center;
}
<Card.Footer className="card-body-padding center-horizontally">
  <label className="support-expand-text-light">Call or email Customer Support to change</label>
</Card.Footer>

输出如下所示: