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

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

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

什么好主意吗?


当前回答

Use:

# Parent
{
  display: table;
}

# Child
{
  display: table-cell;
  width: 100%; /* As large as its parent to center the text horizontally */
  text-align: center;
  vertical-align: middle; /* Vertically align this element on its parent */
}

其他回答

我总是在容器中使用以下CSS,使其内容水平和垂直居中。

display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;

-webkit-box-align: center;
-moz-box-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;

-webkit-box-pack: center;
-moz-box-pack: center;
-ms-flex-pack: center;
-webkit-justify-content: center;
justify-content: center;

在这里查看它的实际操作:https://jsfiddle.net/yp1gusn7/

<!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>

对我来说,这是最好的解决方案:

HTML:

<div id="outer">
    <img src="logo.png">
</div>

CSS:

#outer {
  position: fixed;
  top: 50%;
  left: 50%;
  /* Bring your own prefixes */
  transform: translate(-50%, -50%);
}

您可以尝试以下方法:

If you have a single word or one line sentence, then the following code can do the trick. Have a text inside a div tag and give it an id. Define the following properties for that id. id-name { height: 90px; line-height: 90px; text-align: center; border: 2px dashed red; } Note: Make sure the line-height property is same as the height of the division. Image But, if the content is more than one single word or a line then this doesn’t work. Also, there will be times when you cannot specify the size of a division in px or % (when the division is really small and you want the content to be exactly in the middle). To solve this issue, we can try the following combination of properties. id-name { display: flex; justify-content: center; align-items: center; border: 2px dashed red; } Image These 3 lines of code sets the content exactly in the middle of a division (irrespective of the size of the display). The "align-items: center" helps in vertical centering while "justify-content: center" will make it horizontally centered. Note: Flex does not work in all browsers. Make sure you add appropriate vendor prefixes for additional browser support.

<!DOCTYPE html>
<html>
    <head>

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