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:15

you can try very easy code for this

  display:flex;
  align-items: center;
  justify-content:center;

.box{
  height:90px;
  width:90px;
  background:green;
  display:flex;
  align-items: center;
  justify-content:center;
}
<div class="box">
  Lorem 
</div>

codpen link http://codepen.io/santoshkhalse/pen/xRmZwr

查看更多
时光乱了年华
3楼-- · 2018-12-31 01:16

One of The Best approach is use flex property at parent div and add margin:auto property to element tag

.parent{
    display: flex;
    flex-direction: column;
    flex: 1;
    height:100%;
}

p{
    margin:auto;
}
查看更多
栀子花@的思念
4楼-- · 2018-12-31 01:17
<!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> 
查看更多
步步皆殇っ
5楼-- · 2018-12-31 01:18

This works for me (tested 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 */
}

you can choose other values then 50% fi. 25% to center at 25% of parent

查看更多
不流泪的眼
6楼-- · 2018-12-31 01:19
#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
}
查看更多
宁负流年不负卿
7楼-- · 2018-12-31 01:21
<div class="small-container">
    <span>Text centered</span>
</div>

<style>
.small-container {
    width:250px;
    height:250px;
    border:1px green solid;
    text-align:center;
    position: absolute;
    top: 50%;
    left: 50%;
    -moz-transform: translateX(-50%) translateY(-50%);
    -webkit-transform: translateX(-50%) translateY(-50%);
    transform: translateX(-50%) translateY(-50%);
}
.small-container span{
    position: absolute;
    top: 50%;
    left: 50%;
    -moz-transform: translateX(-50%) translateY(-50%);
    -webkit-transform: translateX(-50%) translateY(-50%);
    transform: translateX(-50%) translateY(-50%);
}
</style>
查看更多
登录 后发表回答