Center Align on a Absolutely Positioned Div

Viewed 125386
div#thing {
  position: absolute;
  top: 0px;
  z-index: 2;
  margin: 0 auto;
}

<div id="thing">
   <p>text text text with no fixed size, variable font</p>
</div>

The div is at the top, but I can't center it with <center> or margin: 0 auto;

9 Answers

Your problem may be solved if you give your div a fixed width, as follows:

div#thing {
    position: absolute;
    top: 0px;
    z-index: 2;
    width:400px;
    margin-left:-200px;
    left:50%;
}

To center it both vertically and horizontally do this:

div#thing {
   position: absolute;
   left: 50%;
   top: 50%;
   transform: translate(-50%, -50%);
}

.contentBlock {
    width: {define width}
    width: 400px;
    position: absolute;
    left: 0;
    right: 0;
    margin-left: auto;
    margin-right: auto;
 
}

Or you can use relative units, e.g.

#thing {
    position: absolute;
    width: 50vw;
    right: 25vw;
}

Yes:

div#thing { text-align:center; }
Related