html - 如何使用 CSS 在 DIV 中垂直居中文本?

标签 html css vertical-alignment

我在使用 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 的顶部:

enter image description here

最佳答案

您的示例展示了在 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/

相关文章:

javascript - 如何使用 jQuery 删除动态添加的行?

html - 使用多个 :not pseudo class 在 CSS 选择器中排除多个 div

css - Bootstrap 导航栏突然坏了

css - 自定义复选框实现中的垂直文本对齐

html - Bootstrap 3底部垂直对齐图像并链接到链接右拉

html - 导航栏垂直对齐不起作用

javascript - 在同一 Canvas 中顺时针旋转一个轮子,逆时针旋转另一个轮子

jQuery 脚本有时被假设值为 0 的变量破坏

html - :1 at the end of css mean or stand for? 是什么意思

html - 如何使用 CSS 预加载图像?