CSS Layout How to - Center an element








Question

We would like to know how to center an element.

Answer


<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
#container {<!--from w  ww . j  av a  2s .c  om-->
  position: relative;
  background: red;
  width: 300px;
  height: 300px;
}

#cen {
  position: absolute;
  width: 150px;
  height: 150px;
  background: grey;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
}

#cen2 img {
  position: absolute;
  background: grey;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
}
</style>
</head>
<body>
  <div id="container">
    <div id="cen"></div>
  </div>
  <br>
  <br>
  <div id="container">
    <div id="cen2">
      <img src="http://placehold.it/200x200">
    </div>
  </div>
</body>
</html>

The code above is rendered as follows: