【问题标题】:CSS - Vertcally align text in a divCSS - 垂直对齐 div 中的文本
【发布时间】:2013-06-20 13:14:50
【问题描述】:

我在 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;
}

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

【问题讨论】:

标签: css vertical-alignment


【解决方案1】:

这可行:

<!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/

【讨论】:

    猜你喜欢
    • 2017-04-16
    • 1970-01-01
    • 2012-12-09
    • 2017-01-17
    • 1970-01-01
    • 2014-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多