在网页上垂直和水平居中两行文本

时间:2015-05-26 17:10:07

标签: html css

我试图让我页面上的所有内容水平和垂直居中,我已经看过多种不同的方式,但是它们似乎没有用,我不确定为什么

我将有三个不同的文本行,所有文本都在不同的H标签中,并且它们都需要位于页面的中心

例如:http://gyazo.com/ffb698f181f428217fc9dc282969c190

@import url(http://fonts.googleapis.com/css?family=Lato:100,300,400,700,900);

body {
  margin: 0;
  padding: 0;
}

img {
  margin: 0;
  padding: 0;
}

h1 {
  color: #fff;
  font-family: 'Lato', sans-serif;
    display: table-cell;
  vertical-align: middle;
  text-align:center;
}

h2 {
  color: #fff;
  font-family: 'Lato', sans-serif;
}

#content {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 100%;
  height: 100%;
  text-align: center;
  background:#000;
  background-size: cover;
  background-position: 50% 50%;
  display: table;
	
}
<!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 http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="style.css">

<title>Callum Watson</title>
        
</head>
 
<body>

<div id="content">
  <h1> CALLUM WATSON </h1>
  <h2>all css?! WHUT.</h2>
</div>
</body>
</html>

我不确定为什么会这样。

2 个答案:

答案 0 :(得分:1)

使用display: table-cell;和&#39; new&#39;的组合单位vw(视口宽度)和vh(视口高度):

&#13;
&#13;
body {
  margin: 0;
  padding: 0;
}

#content {
  color: #FFF;
  width: 100vw;
  height: 100vh;
  text-align: center;
  background:#000;
  display: table-cell;
  vertical-align: middle;
  font-family: 'Lato', sans-serif;
}
&#13;
<div id="content">
  <h1> CALLUM WATSON </h1>
  <h2>all css?! WHUT.</h2>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

尝试使用h1{display:block}代替table-cell

&#13;
&#13;
@import url(http://fonts.googleapis.com/css?family=Lato:100,300,400,700,900);

body {
  margin: 0;
  padding: 0;
}

img {
  margin: 0;
  padding: 0;
}

h1 {
  color: #fff;
  font-family: 'Lato', sans-serif;
    display: block;
  vertical-align: middle;
  text-align:center;
}

h2 {
  color: #fff;
  font-family: 'Lato', sans-serif;
}

#content {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 100%;
  height: 100%;
  text-align: center;
  background:#000;
  background-size: cover;
  background-position: 50% 50%;
  display: table;
	
}
&#13;
<!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 http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="style.css">

<title>Callum Watson</title>
        
</head>
 
<body>

<div id="content">
  <h1> CALLUM WATSON </h1>
  <h2>all css?! WHUT.</h2>
</div>
</body>
</html>
&#13;
&#13;
&#13;