CSS Layout How to - Vertically center text in div








Question

We would like to know how to vertically center text in div.

Answer


<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
div {<!--   ww  w. j a v  a2  s.c  om-->
  background: blue;
  color: white;
  font-family: sans-serif;
  text-align: center; /* horizontally center */
  height: 500px;
}

div span {
  height: 100%;
  vertical-align: middle;
  display: inline-block;
}

div h1 {
  margin: 0;
  vertical-align: middle;
  display: inline-block;
}
</style>

</head>
<body>
  <div>
    <span></span>
    <h1>Text</h1>
  </div>
</body>
</html>

The code above is rendered as follows: