CSS center text (horizontally and vertically) insi

2018-12-31 00:25发布

I have a div set to display:block. (90px height and width) and I have some text inside.

I need the text to be aligned in the center both vertically and horizontally.

I have tried text-align:center, but it doesn't do the horizontal part so I tried vertical-align:middle but it didn't work.

Any ideas?

标签: html css
23条回答
心情的温度
2楼-- · 2018-12-31 01:23

I always use the following CSS for a container, to center it's content horizontally and vertically.

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;

See it in action here: https://jsfiddle.net/yp1gusn7/

查看更多
浮光初槿花落
3楼-- · 2018-12-31 01:23

Apply style:

position: absolute;
top: 50%;
left: 0;
right: 0;

Your text would be centered irrespective of its length.

查看更多
孤独寂梦人
4楼-- · 2018-12-31 01:24

Give this css class to the targeted

.centered {
  width: 150px;
  height: 150px;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  background: red; /* not necessary just to see the result clearly */
}
<div class="centered">This text is centered horizontally and vertically</div>

查看更多
骚的不知所云
5楼-- · 2018-12-31 01:24
<!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>
查看更多
大哥的爱人
6楼-- · 2018-12-31 01:25

.cell-row {display: table; width: 100%; height: 100px; background-color: lightgrey; text-align: center}
.cell {display: table-cell}
.cell-middle {vertical-align: middle}
<div class="cell-row">
  <div class="cell cell-middle">Center</div>
</div>

查看更多
登录 后发表回答