A way to do this would include a small amount of js, but not so much. Although first I will go through css:
First, you need to add:
left: 50%;
This gives the end of the div to the left halfway through the page. Then give it a class so that we can reference it in javascript, for example:
<div style='position:relative'> <div class='center-absolute'>Content</div> </div>
So we can reference it in css and js. We use a class because you should only use an identifier for a single element.
Here is the css you will need for .center-absolute :
.center-absolute { position: absolute; left: 50%; }
Then for js. Since there may be several elements, we need a for loop to iterate between them:
var $centerAbsolute = document.getElementsByClassName('center-absolute'); for (i = 0; i < $centerAbsolute.length; i++) { $centerAbsolute[i].style.marginLeft = $centerAbsolute[i].offsetWidth / 2 * -1 + 'px'; }
This repeats through all elements with the center-absolute class and gives them a field to the left of minus half the width of the element that centers it.
Here is a demonstration of the working script:
http://jsfiddle.net/Hive7/FqJ7T/
Hive7 source share