简体   繁体   中英

full page background image resizable - maintain aspect-ratio

I need a simple jquery solution to add a background image to my page filling it entirely, but keeping the aspect ratio and vertical and horizontal centered position.

there are several plugins out here but I don't want to use any plugin.

thanks in advance.

This code will do what you want..

$(function(){

    var stretcher = $('#background-container > img'),
        element = stretcher[0],
        currentSize = { width: 0, height: 0 },
        $document = $(document);

    $(window).resize(function () {
        var w = $document.width();
        var h = $document.height();

        if (currentSize.width != w || currentSize.height != h) {
            stretcher.width(w).height('auto');
            if (h > element.height) {
                stretcher.width('auto').height(h);
            }
            currentSize.width = w;
            currentSize.height = element.width;
        }
    })

    $(window).load(function () {
        $(this).trigger('resize');
    });

});

Set your HTML like this

<div id="page">
    Your page contents here..
</div>
<div id="background-container">
      <img src="path/to/image" />
</div>

and your CSS like

#background-container{
    position:absolute;
    z-index:1;
    top:0;
    left:0;
    width:100%;
    height:100%;
    overflow:hidden;
}

#page{
    position:relative;
    z-index:5;
}

Demo at http://jsfiddle.net/gaby/3YLQf/

Or you could use the CSS property :

background-size: cover

This will scale the image, while preserving its intrinsic aspect ratio (if any), to the smallest size such that both its width and its height can completely cover the background positioning area.

You can control how your image is aligned within the viewport by using the background-position property

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM