How can I center an absolutely positioned element in a div?

Ish picture Ish · Nov 21, 2009 · Viewed 1.2M times · Source

I need to place a div (with position:absolute;) element in the center of my window. But I am having problems doing so, because the width is unknown.

I tried this. But it needs to be adjusted as the width is responsive.

.center {
  left: 50%;
  bottom: 5px;
}

How can I do it?

Answer

Matthias Weiler picture Matthias Weiler · Nov 25, 2011

This works for me:

#content {
  position: absolute; 
  left: 0; 
  right: 0; 
  margin-left: auto; 
  margin-right: auto; 
  width: 100px; /* Need a specific value to work */
}
<body>
  <div>
    <div id="content">
      I'm the content
    </div>
  </div>
</body>