On this page, I would like to horizontally center the main #container div relative to the page. Normally I would achieve this by adding a CSS rule,
#container { margin: 0 auto }
However, the layout of this page (which I did not write), uses absolute positioning for #container and most of its child elements, so this property has no effect.
Is there any way I can achieve this horizontal centering without rewriting the layout to use static positioning? I've no problem with using JavaScript/JQuery if that's the only way to achieving my objective.
Same as @rquinn answer but this will adjust to any width. Check this demo
http://jsfiddle.net/Starx/V7xrF/1/
HTML:
<div id="container"></div>
CSS:
* { margin:0;padding:0; }
#container {
width:50px;
position:absolute;
height:400px;
display:block;
background: #ccc;
}
Javascript
function setMargins() {
width = $(window).width();
containerWidth = $("#container").width();
leftMargin = (width-containerWidth)/2;
$("#container").css("marginLeft", leftMargin);
}
$(document).ready(function() {
setMargins();
$(window).resize(function() {
setMargins();
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With