Center Alignment on an 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 focus it on <center> or margin: 0 auto ;
Your problem can be solved if you specified your fixed div 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 for the party, but I thought I would give an answer here for people who need to position the absolute element horizontally when you don't know its exact width.
Try the following:
// Horizontal example. div#thing { position: absolute; left: 50%; transform: translateX(-50%); } The same technique can be applied because when you may need vertical alignment, simply adjust the properties as follows:
// Vertical example. div#thing { position: absolute; top: 50%; transform: translateY(-50%); } If you need to have a relative width (in percent), you can wrap your div in absolute positioning:
div#wrapper { position: absolute; width: 100%; text-align: center; } Remember that in order to position an element absolutely, the parent element must be relative.
I had the same problem and my limitation was that I could not have a predefined width. If your item does not have a fixed width, try this
div#thing { position: absolute; top: 0px; z-index: 2; left:0; right:0; } div#thing-body { text-align:center; } then change your html so it looks like
<div id="thing"> <div id="thing-child"> <p>text text text with no fixed size, variable font</p> </div> </div> To center it vertically and horizontally, do this:
div#thing { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); } Yes:
div#thing { text-align:center; }