Centering positioned absolute elements

Tuesday, May 1, 2012

The other day I was needing to centre a positioned element and because the element had position: absolute; attached to it margin: auto; becomes null and void and instead you’re required to position it using left: 10px; top: 10px; etc.

There are many hacks for this including wrapping the positioned div in a wrapper div with the correct width and then centering that using margin: auto;, also the old left: -50%; hack on the div but I always found this buggy.

I managed to get the following to work however in every browser except IE7:

div {
width: 100px;
left: 0;
margin: auto;
position: absolute;
right: 0;

Yep, keeping your margin: auto; on but then setting both a left and right position of zero seems to make the div align in the centre!

So there you go, no more extra divs and strange markup! As mentioned before this didn’t work for me when testing in IE7 but then again I guess you could always use the left: -50%; fallback for lower versions of IE if required.