text te...">

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 ;

+87
html css xhtml
Oct 31 '08 at 8:10
source share
7 answers

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%; } 
+147
Oct 31 '08 at 8:27
source share
 div#thing { position: absolute; width:400px; right: 0; left: 0; margin: auto; } 
+94
Dec 10 '12 at 17:45
source share

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%); } 
+32
Aug 16 '16 at 10:56 on
source share

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.

0
Jun 20 '16 at 12:04 on
source share

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> 
0
Jul 11 '16 at 19:40
source share

To center it vertically and horizontally, do this:

 div#thing { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); } 
0
Jul 06 '19 at 15:51
source share

Yes:

 div#thing { text-align:center; } 
-22
Jan 15 '09 at 15:14
source share



All Articles