CSS Layout How to - Position div Absolute Center








Question

We would like to know how to position div Absolute Center.

Answer


<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
#center-1 {<!--from w w w .j  ava2  s .c  om-->
  position: absolute;
  width: 100px;
  height: 100px;
  left: 50%;
  top: 50%;
  margin-left: -50px; /*subtract by half width*/
  margin-top: -50px; /*subtract by half height*/
  background: rgba(10, 10, 10, 1);
  z-index: 1;
}

#center-2 {
  position: absolute;
  width: 300px;
  height: 300px;
  left: 50%;
  top: 50%;
  margin-left: -150px;
  margin-top: -150px;
  background: rgba(110, 10, 10, .1);
  z-index: 0;
}
</style>
</head>
<body>
  <div id="center-1"></div>
  <div id="center-2"></div>
</body>
</html>

The code above is rendered as follows: