Search code examples
htmlcsspositionrepeat

How do I make a HTML background image extend its width outside of the parent DIV


I have a header image which I want to be positioned horizontally, stretched across the top of a website. The width needs to be the same as the browser window.

This is exactly the same as the dark bar at the top of StackOverflow.

My wrapper DIV has a fixed width therefore my image is appearing only for the width of the DIV. How can I make it the full width of the browser window?


Solution

  • The short answer is that you can't. Background images will always be contained within it's parent element. What you could try doing is instead of using the image as a background on your parent element, you could drop it into it's own element and bring that element outside of the container.

    For instance:

    <div class="container">
        <div class="headerImage">
            <ul class="navigation">
                <li><a href="">Link One</a></li>
                <li><a href="">Link Two</a></li>
            </ul>
        </div>
        <div class="otherContent"></div>
    </div>
    

    And then in your CSS:

    .container {
        position: static; // This allows the image to break outside of it's container.
        margin: 0 auto;
        width: 960px;
    }
    
    .headerImage {
        background: url(yourImage.png) center top no-repeat transparent;
        display: block;
        position: absolute; // This breaks it out of the normal document flow.
        top: 0; left: 0;
        width: 100%; // This will expand to fill the width of the window.
        height: 65px; // Or whatever height you want.
        z-index: 10; // Play with this number for layering.
    }
    

    Good luck with your project.