Search code examples
jquerycsspositioningcss-position

Center div horizontally


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.


Solution

  • 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();    
        });
    });