Search code examples
jquerycssviewportcentering

Center an element whose width is beyond the viewport


I would like to center an element whose width is beyond the viewport (i.e. element = 1000px / viewport = 800px). I already tried basic CSS (margin = 0 auto) but it doesn't work. Would be great if somebody could help me out!

I have three child elements (.project) whose widths are calculated through jQuery. Moreover, the sum of those three child elements are the width of my parent element (#projects).

Here is a jsFiddle.

Cheers

$(window).on( "resize", function () {
    var projectWidth = ( $(window).width() / 2.8 );
    $(".project").css({ width : projectWidth.toFixed() });

    var projectSum = 0;
    $("#projects .project").each( function(){ projectSum += $(this).width(); });
    $(".container").css({ width : projectSum });        
}).resize();

Solution

  • This is very simple using CSS. Here is an example where the body is set to be 400px wide and an element of 600px is aligned in the middle.

    The maths is simply (containerWidth - divWidth) / 2 then use this value as margin-left and margin-right which you can use with dynamic width from JS.

    http://jsfiddle.net/da8y64ww/1/

    body {
        width:400px;
        border:1px dotted blue;
        margin:0 auto;
    }
    #foo {
        width:600px;
        height:100px;
        border:1px solid green;
        margin-left:-100px;
        margin-right:-100px;
    }