Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 379
Emilio Yero Avatar asked Dec 16 '22 11:12

Emilio Yero


2 Answers

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/

like image 120
Gabriele Petrioli Avatar answered Mar 24 '23 00:03

Gabriele Petrioli


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

like image 22
Ahmad Alfy Avatar answered Mar 24 '23 02:03

Ahmad Alfy