Search code examples
csshtmlcenter

Div to show in centre of page with background stretching across


Looking at centering a div across all browser and screen resolutions. Seen that the left 50% with margin-left of the div width to be quite common but wrapping the div completely in a containing div cuts off the background of my div.

My div will spread across the whole of the screen with a light grey background with an inner div with my content within.

I have tried using percentages and pixels but cannot get it to sit central in both 1920 wide and 1200 wide.

css is as follows:

#default-upper-strap {

background-color: #ddd;
width: 109.61%;
margin-top: 25px;
z-index: 99999;
position: relative;
overflow: hidden;
padding-left: 23px;
margin-left: -8px;
max-width: 1920px;
}

#default-strap-left {
width: 810px;
height: 100%;
float: left;
margin-left: 21%;
}

Solution

  • Why don't you start with the following:

    <div class="default-upper-strap">
        <div class="default-strap-left">Some content...</div>
    </div>
    
    body {
        margin: 0;
    }
    .default-upper-strap {
        background-color: #ddd;
        width: 100%;
        max-width: 1920px;
        margin: 25px auto 0 auto;
        padding-left: 0px;
    }
    .default-strap-left {
        width: 810px;
        height: 100%;
        margin: 0 auto;
        border-top: 1px dashed blue;
    }
    

    Use margin: 0 auto to center the child element within the parent container.

    When the parent container reaches its maximum width, the margin: 25px auto 0 auto rule will take care of centering the parent container if this is what you want.

    See demo at: http://jsfiddle.net/audetwebdesign/JqxY8/