我应该如何更改此html代码段,以便文本Hello World垂直位于屏幕中间?

时间:2017-02-27 15:23:25

标签: html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta content="en-us" http-equiv="Content-Language" />
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Title</title>
</head>
<body style="width: 100%; height: 100%">
    <table cellspacing="1" style="width: 100%; height: 100%">
        <tr>
            <td valign="middle" align="center">
            <h1>Hello World</h1>
            </td>
        </tr>
    </table>

</body>

</html>

该html片段的结果是“Hello World”一词位于屏幕顶部。我做了一切使它在中间。我该怎么办?

我尝试了另一种使用垂直对齐方式的方法

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta content="en-us" http-equiv="Content-Language" />
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>How to get Sexier Avatar in IMVU 2</title>
</head>
<body style="width: 100%; height: 100%">
<div style="height: 100%;width: 100%;vertical-align: middle">
<h1>Click here to Get Game and See Yourself</h1>
</div>

</body>

</html>

我清楚地说div的垂直对齐应该是中间的。它没有用。

看起来身体的大小并非全屏。如何全屏显示?

2 个答案:

答案 0 :(得分:1)

<!doctype HTML>
<html>
<head>
<meta content="en-us" http-equiv="Content-Language" />
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Title</title>
<style>
#centerInScreen {
position:absolute;
top:0;
left:0;
width:100%;
height:100%;
}
#centerInScreen h1 {
position: relative;
top: 50%;
transform: translateY(-50%); 
}
</style>
</head>
<body>
<div id="centerInScreen">
<h1>Hello World!</h1>
</div>
</body>
</html>

使用此选项以屏幕为中心。

答案 1 :(得分:0)

使用CSS

<div class="center">Hello World</div>

.center {
    position: absolute;
    width: 100px;
    height: 50px;
    top: 50%;
    left: 50%;
    margin-left: -50px; /* margin is -0.5 * dimension */
    margin-top: -25px; 
}​