CSS - 垂直对齐 div 中的文本

标签 css vertical-alignment

我在 SO 中检查了很多答案,最常见的解决方案是将 div 的 display 设置为 table-cellinline-block 并放置 vertical-align: middle

因此,以下是我的 HTML 代码。

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
        <link rel="stylesheet" type="text/css" href="css/ad.css" />
        <title>Ad</title>
    </head>
    <body>
        <div id="initial-div">
            Check out our amazing offer
        </div>
    </body>
</html>

CSS代码如下

body {
    overflow:hidden;
    height:100%;
    min-height: 100%;
    width: 100%;
    color: #ffffff;
    background-color:aliceblue;
}

#initial-div{
    position:absolute;
    top:0;
    bottom:0;
    right:0;
    left:0;
    color: #000;
    display: inline-block;
    vertical-align: middle;
    text-align: center;
    background-color: #ffd800;
}

但是,文本似乎并没有垂直居中。我哪里出错了?

最佳答案

这会起作用:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
        <link rel="stylesheet" type="text/css" href="css/ad.css" />
        <title>Ad</title>
    </head>
    <body>
        <div id="initial-div">
            <div>Check out our amazing offer</div>
        </div>
    </body>
</html>


body {
    overflow:hidden;
    height:100%;
    min-height: 100%;
    width: 100%;
    color: #ffffff;
    background-color:aliceblue;
}

#initial-div{
    position:fixed;
    height: 100%;
    color: #000;
    background-color: #ffd800;
    width: 100%;
}
#initial-div div{
    text-align: center;
    position: relative;
    top: 50%;
    margin-top: -5px; /* height/2 */
}

http://jsfiddle.net/zpFym/

关于CSS - 垂直对齐 div 中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17205544/

相关文章:

html - 带方向箭头的纯 CSS 菜单

css - 带有背景图像的标题文本垂直居中(1 或 2 行)

css - 相对定位元素的负上边距问题(垂直对齐)

css - Material 设计图标垂直对齐, Chrome

vertical-alignment - 如何在PlantUML图上垂直显示 block ?

html - 如何在 Angular2 中设置兄弟组件的样式?

javascript - 试图改变点击宽度

javascript - 使用 JavaScript 的 Google map 无法在 jQuery 选项卡中正确显示

javascript - Bootstrap 3 弹出窗口显示一个并隐藏其他不起作用

html - 内联 block 元素不垂直对齐省略号溢出