CSS Layout How to - Center Absolutely Positioned elements








Question

We would like to know how to center Absolutely Positioned elements.

Answer


<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
.wrapper {<!--   ww  w .j  a  v a 2  s.  co m-->
  border: 2px dotted blue;
  position: relative;
  width: 654px;
  height: 100px;
}

.outer {
  position: absolute;
  width: 400px;
  height: 400px;
  background: #999;
}

.inner {
  position: absolute;
  width: 200px;
  height: 400px;
  background: #666;
}

.center {
  left: 0;
  right: 0;
  margin-left: auto;
  margin-right: auto;
}
</style>
</head>
<body>
  <div class="wrapper">
    <div class="outer center">
      <div class="inner center"></div>
    </div>
  </div>
</body>
</html>

The code above is rendered as follows: