HTML Element Style How to - Vertically and horizontally align an image in a div








Question

We would like to know how to vertically and horizontally align an image in a div.

Answer


<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
#img_holder {<!--from w w w . j av a2s  .  c  o m-->
  background-color: #EEE;
  height: 500px;
  width: 550px;
  position: relative;
}

#image {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 300px;
  height: 300px;
  margin-top: -150px; /* Half the height */
  margin-left: -150px; /* Half the width */
}
</style>
</head>
<body>
  <div id="img_holder">
    <img id="image" src="http://www.java2s.com/style/download.png">
  </div>
</body>
</html>

The code above is rendered as follows: