HTML Element Style How to - Center an image vertically and horizontally according to current window size








Question

We would like to know how to center an image vertically and horizontally according to current window size.

Answer


<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
img {<!--  ww w.jav a 2  s  .co  m-->
  position: fixed;
  top: 50%;
  left: 50%;
  margin-top: -16px;
  margin-left: -16px;
}
</style>
</head>
<body>
  <img
    src="http://www.java2s.com/style/download.png"
    alt="test" />
</body>
</html>

The code above is rendered as follows: