CSS Layout How to - Center an image vertically and horizontally








Question

We would like to know how to center an image vertically and horizontally.

Answer


<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
html, body {<!--   w  w w.  ja v  a2  s . co m-->
  height: 100%;
  width: 100%;
}

#overlay {
  position: relative;
  background: black;
  width: 100%;
  height: 100%;
}

#overlay img {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  outline: 1px dotted yellow;
}
</style>
</head>
<body>
  <div id="overlay">
    <img src="http://placehold.it/200x200" />
  </div>
</body>
</html>

The code above is rendered as follows: