Center Align on a Absolutely Positioned Div
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
;
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%;
}
div#thing
{
position: absolute;
width:400px;
right: 0;
left: 0;
margin: auto;
}
I know I'm late to the party, but I thought I would provide an answer here for people who need to horizontally position an absolute item, when you don't know its exact width.
Try this:
// Horizontal example.
div#thing {
position: absolute;
left: 50%;
transform: translateX(-50%);
}
The same technique can also be applied, for when you might need vertical alignment, simply by adjusting the properties like so:
// Vertical example.
div#thing {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
To center it both vertically and horizontally do this:
div#thing {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}