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

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

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

什么好主意吗?


当前回答

调整线高度以获得垂直对齐。

line-height: 90px;

其他回答

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

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 */
}

你可以在父div中使用flex属性,并将margin:auto属性添加到子条目中:

.parent {
    display: flex;
    /* You can change this to `row` if you want the items side by side instead of stacked */
    flex-direction: column;
}

/* Change the `p` tag to what your items child items are */
.parent p {
    margin: auto;
}

你可以在这里看到更多flex的选项:https://css-tricks.com/snippets/css/a-guide-to-flexbox/

GRID

.center {
    display: grid;
    justify-items: center;
    align-items: center;
}

.center { 显示:网格; justify-items:中心; 对齐项目:中心; } .box { 宽度:200 px; 身高:100 px; 背景:红色; } <div class="box center">我的文本</div>

调整线高度以获得垂直对齐。

line-height: 90px;