Javascript Style How to - Center an absolute positioned div with an unfixed width








Question

We would like to know how to center an absolute positioned div with an unfixed width.

Answer


<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
.center-absolute {<!-- ww  w  .  jav  a 2s . c  om-->
  position: absolute;
  left: 50%;
}
</style>
<script type='text/javascript'>
window.onload=function(){
    var $centerAbsolute = document.getElementsByClassName('center-absolute');
    for (i = 0; i < $centerAbsolute.length; i++) {
        $centerAbsolute[i].style.marginLeft = $centerAbsolute[i].offsetWidth / 2 * -1 + 'px';
    }
}
</script>
</head>
<body>
  <div style='position: relative'>
    <div class='center-absolute'>Content</div>
  </div>
</body>
</html>

The code above is rendered as follows: