Search code examples
htmlimagecssbackground-image

know of a good CSS-technique for a full-screen background image?


i've look around online and tried various ways to go about this, but haven't managed to find one technique that works for me. i'd like my website's background image to be centered, fill the entire browser screen, and work with responsive design.

is there an easy technique, besides the CSS3/background-size: cover? that just didn't work at ALL for me (not sure why...).


Solution

  • If you're not opposed to a solution involving HTML in addition to CSS, you can simulate the background-size: cover behavior with an img tag.

    HTML:

    <body>
        <div id="image-matte">
            <img src="..."/>
        </div>
    
        ... Page content below ...
    
    </body>
    

    CSS:

    #image-matte {
        position: fixed;
        top: 0%;
        left: -50%;
        width: 200%;
        height: 200%;
    }
    
    #image-matte img {
        display: block;
        margin: auto;
        min-height: 50%;
        min-width: 50%;
    }
    
    /* Covers the image to prevent pointer interaction */
    #image-matte:after {
        content: '';
        display: block;
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
    }
    

    EDIT: To get a vertically AND horizontally centered background image, you'll need to create a table/table-cell relationship between the wrapper div, and an inner div that holds the image itself... The HTML and CSS would look like this:

    HTML:

    <div id="image-matte">
        <div>
            <img src="..."/>
        </div>
    </div>
    

    CSS:

    #image-matte {
        position: fixed;
        display: table;
        top: -50%;
        left: -50%;
        width: 200%;
        height: 200%;
        text-align: center;
    }
    #image-matte div {
        vertical-align: middle;
        display: table-cell;
    }
    #image-matte img {
        position: relative;
        text-align: center;
        min-height: 50%;
        min-width: 50%;
    }
    
    /* Covers the image to prevent pointer interaction */
    #image-matte:after {
        content: '';
        display: block;
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
    }
    

    Working example: http://jsfiddle.net/qkpvb/