您可以尝试以下基本方法:
div {
height: 100px;
line-height: 100px;
text-align: center;
border: 2px dashed #f69c55;
}
<div>
Hello World!
</div>
但是,它仅适用于一行文本,因为我们将行的高度设置为与包含框元素相同的高度。
这是垂直对齐文本的另一种方法。此解决方案适用于一行和多行文本,但仍需要一个固定高度的容器:
div {
height: 100px;
line-height: 100px;
text-align: center;
border: 2px dashed #f69c55;
}
span {
display: inline-block;
vertical-align: middle;
line-height: normal;
}
<div>
<span>Hello World!</span>
</div>
CSS只是通过设置的line-height等于其高度来<div>
调整的大小,垂直居中对齐,然后使用来将inline- block设置为。然后,将的行高设置回正常,因此其内容将自然地在块内流动。<span>``<div>``<span>``vertical-align: middle``<span>
这是另一个选项,可能在不支持display: table
和的display: table- cell
较旧的浏览器(主要是InternetExplorer7)上不起作用。使用CSS我们模拟表的行为(因为表支持垂直对齐),并且HTML与第二个示例相同:
div {
display: table;
height: 100px;
width: 100%;
text-align: center;
border: 2px dashed #f69c55;
}
span {
display: table-cell;
vertical-align: middle;
}
<div>
<span>Hello World!</span>
</div>
此技术使用绝对定位的元素将top,bottom,left和right设置为0。在SmashingMagazine的CSS中的绝对水平和垂直居中中_ 对此进行了详细介绍。
div {
display: flex;
justify-content: center;
align-items: center;
height: 100px;
width: 100%;
border: 2px dashed #f69c55;
}
<div>
<span>Hello World!</span>
</div>