How do I vertically center text with CSS?
I have a div element which contains text, and I want to align the contents of this div vertically center.
Here is my div style:
#box {
height: 170px;
width: 270px;
background: #000;
font-size: 48px;
color: #FFF;
text-align: center;
}
<div id="box">
Lorem ipsum dolor sit
</div>
你可以尝试这种基本的方法:
div {
height: 90px;
line-height: 90px;
text-align: center;
border: 2px dashed #f69c55;
}
<div>
Hello World!
</div>
Another way (not mentioned here yet) is with Flexbox.
Just add the following code to the container element:
display: flex;
justify-content: center; /* align horizontal */
align-items: center; /* align vertical */
Flexbox demo 1
.box {
height: 150px;
width: 400px;
background: #000;
font-size: 24px;
font-style: oblique;
color: #FFF;
text-align: center;
padding: 0 20px;
margin: 20px;
display: flex;
justify-content: center;
/* align horizontal */
align-items: center;
/* align vertical */
}
<div class="box">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh
</div>
You can easily do this by adding the following piece of CSS code:
display: table-cell;
vertical-align: middle;
That means your CSS finally looks like:
#box {
height: 90px;
width: 270px;
background: #000;
font-size: 48px;
font-style: oblique;
color: #FFF;
text-align: center;
margin-top: 20px;
margin-left: 5px;
display: table-cell;
vertical-align: middle;
}
<div id="box">
Some text
</div>
链接地址: http://www.djcxy.com/p/1104.html
上一篇: Vim:左右移动窗口?
下一篇: 我如何垂直居中文本与CSS?