CSS Layout How to - Center a relatively positioned element with unknown width








Question

We would like to know how to center a relatively positioned element with unknown width.

Answer


<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
body {<!--from w  w  w  . ja  v a  2s  .com-->
  background: #EEE;
  text-align: center;
}

#box {
  background: #AAA;
  display: inline-block;
  height: 90px;
  margin: 0 auto;
  padding: 6px;
  position: relative;
}

#child {
  background: #DDD;
  bottom: 16px;
  height: 20px;
  left: 16px;
  position: absolute;
  width: 20px;
}
</style>
</head>
<body>
  <div id="box">
    <h1>Box with an Unknown Width</h1>
    <div id="child"></div>
  </div>
</body>
</html>

The code above is rendered as follows: