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

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

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

什么好主意吗?


当前回答

你可以尝试非常简单的代码:

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

.box { 身高:90 px; 宽度:90 px; 背景:绿色; 显示:flex; 对齐项目:中心; justify-content:中心; } < div class = "盒子" > Lorem < / div >

代码依赖链接:http://codepen.io/santoshkhalse/pen/xRmZwr

其他回答

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

添加行显示:table-cell;到该div的CSS内容。

只有表格单元格支持vertical-align: middle;,但是你可以把[table-cell]定义给div…

一个活生生的例子在这里:http://jsfiddle.net/tH2cc/

div{
    height: 90px;
    width: 90px;
    text-align: center;
    border: 1px solid silver;
    display: table-cell; /* This says treat this element like a table cell */
    vertical-align:middle; /* Now we can center vertically like in a TD */
}

我总是在容器中使用以下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/

将这个CSS类赋给目标<div>:

.centered { 宽度:150 px; 身高:150 px; 显示:flex; 对齐项目:中心; justify-content:中心; text-align:中心; 背景:红色;/*不需要只是为了清楚地看到结果*/ } <div class="居中">这个文本水平和垂直居中</div>

你可以在父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/