我有一个 <div>
包含文本的元素,我想对齐此 <div>
的内容垂直居中。
这是我的<div>
风格:
#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: 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 只是调整 <div>
的大小, 垂直居中对齐 <span>
通过设置 <div>
的行高等于它的高度,并使 <span>
带有 vertical-align: middle
的内联 block .然后它将 <span>
的行高设置为正常值。 ,所以它的内容会在 block 内自然流动。
还有一个选项,它可能不适用于旧的 browsers that don't support display: table
and display: table-cell
(基本上只是 Internet Explorer 7)。使用 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>
此技术使用绝对定位元素,将顶部、底部、左侧和右侧设置为 0。在 Smashing Magazine 中的一篇文章中进行了更详细的描述, Absolute Horizontal And Vertical Centering In CSS .
div {
display: flex;
justify-content: center;
align-items: center;
height: 100px;
width: 100%;
border: 2px dashed #f69c55;
}
<div>
<span>Hello World!</span>
</div>
https://stackoverflow.com/questions/8865458/