我在使用 CSS 将 DIV 中的文本垂直居中时遇到问题。我已经在 SO 和其他地方关注了相关的答案,但似乎无法让它发挥作用。我的简化场景是
<div class="outer">
<div class="header-title">
<span class="header-text">This is the title</span>
</div>
</div>
和
div.outer {
position: relative;
height: 200px;
border-style: solid;
border-width:1px;
}
div.header-title {
position: absolute;
font-size: 36px;
height: 100%; /* required */
color: green;
border-style: dashed;
border-width:1px;
}
span.header-text {
vertical-align: middle;
border-style: dotted;
border-width:1px;
}
但结果(在 Safari 中)将“header-text”span
留在“header-title”div
的顶部:
最佳答案
您的示例展示了在 div 中垂直居中元素的良好解决方法:
display: table-cell;
vertical-align: middle;
因此将它添加到您的 div CSS 中:
div.header-title {
position: absolute;
font-size: 36px;
height: 100%; /* required */
color: green;
display: table-cell;
vertical-align: middle;
border-style: dashed;
border-width:1px;
}
关于html - 如何使用 CSS 在 DIV 中垂直居中文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21467093/