简体   繁体   English

使用“垂直对齐”在div中居中放置文本

[英]Centering text in div using 'vertical-align' not working

the title pretty much sums it up. 标题几乎总结了一下。 I have the following code: 我有以下代码:

<div class="container">
   <p>Hello world</p>
</div>

And CSS: 和CSS:

.container{
    width: 100%;
    height: 50px;    
    background-color: lightblue;
    vertical-align: middle; /* Why you no work!?!? */
}

But the text is not vertically aligning in the div. 但是文本在div中不是垂直对齐的。 I'm clearly missing something here or don't understand a certain concept. 我在这里显然缺少了一些东西,或者不了解某个概念。 Anybody tell me what's happening? 有人告诉我发生了什么事吗?

Thanks! 谢谢!

if you have single line text add this to your css. 如果您有单行文本,请将其添加到CSS。

.container > p{ line-height:50px; .container> p {line-height:50px; } }

To use vertical-align: middle , you need to use display: inline-block . 要使用vertical-align: middle ,需要使用display: inline-block

Your code will change to this: 您的代码将更改为:

.container{
    display: inline-block; /* This is the line you need to introduce */
    width: 100%;
    height: 50px;    
    background-color: lightblue;
    vertical-align: middle;
}

You can take a look at the demo . 您可以看一下演示

Update 更新资料

Using display: table for .container and display: table-cell for .container p makes it work. 使用display: table for .containerdisplay: table-cell for .container p使它起作用。

Updated demo 更新的演示

.container{
    display: table;
    width: 100%;
    height: 200px;
    background-color: lightblue;
    vertical-align: middle;
}
.container p {
    display: table-cell;
    vertical-align: middle;
}

Vertical alignment in CSS is not as straightforward as horizontal alignment. CSS中的垂直对齐方式不如水平对齐方式简单。

Depending on your case and the content you need to apply one technique or another. 根据您的情况和内容,您需要应用一种或另一种技术。

You can check this link for different techniques: 您可以检查此链接以了解其他技术:

http://www.vanseodesign.com/css/vertical-centering/ http://www.vanseodesign.com/css/vertical-centering/

In short, vertical-align: center; 简而言之,垂直对齐:居中; is not going to work in your case 在你的情况下是行不通的

Add to your container the display property as follows: 将显示属性添加到您的容器中,如下所示:

.container{
    width: 100%;
    height: 50px;    
    background-color: lightblue;
    display:inline-block; 
    vertical-align: middle; 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM