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

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

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

什么好主意吗?


当前回答

这招对我很管用:

.center-stuff{
    text-align: center;
    vertical-align: middle;
    line-height: 230px; /* This should be the div height */
}

其他回答

您可以尝试以下方法:

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.

.cell-row{显示:表;宽度:100%;身高:100 px;background - color: lightgrey;text-align:中心} .cell{显示:table-cell} .cell-middle {vertical-align: middle} < div class = " cell-row”> <div class="cell - cell-middle">Center</div> < / div >

div { 身高:90 px; 行高:90 px; text-align:中心; 边界:2px虚线#f69c55; } < div > 你好,世界! ! < / div >

应用样式:

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

无论长度如何,文本都将居中。

这招对我很管用:

.center-stuff{
    text-align: center;
    vertical-align: middle;
    line-height: 230px; /* This should be the div height */
}