Getting background image height using "background-size: contain"

So, I have a gallery of images. Each image is background-imagethat is stretched across the page.

In order for each image to use the maximum available width, I give it the following background size:

background-size: 100% auto;

However, some of the images are higher than the available screen height.

To make sure the image is fully visible (at least using the scroll bars), I will need to tell the element the bodyheight of the modified background image.

However, there seems to be no way to get the height of the resized image in JavaScript.

It's true? Should I resort to normal image elements?

There are many approaches to getting the size of a static background image, for example How to get the size of a background image in jQuery? but they clearly do not apply here.

+4
source share
2 answers

The key is to use the dimensions of the static image, calculate the proportions of the image, and then use the actual dimensions of the element to determine the calculated sizes of the resized image.

For example, suppose you had the following:

html, body { height:100%; }
body {
    background-image: url('http://placehold.it/50x100');
    background-repeat: no-repeat;
    background-size: 100% auto;
}

50x100, , 100% body. body . , . 800px, (400*100)/50 = 800

var img = new Image();
img.src = $('body').css('background-image').replace(/url\(|\)$/ig, "");

$(window).on("resize", function () {
    $('body').height($('body').width() * img.height / img.width);
}).resize();

Pure JS:

var img = new Image();
img.src = window.getComputedStyle(document.body).getPropertyValue("background-image").replace(/url\(|\)$/ig, "");

function resize(){
    var bgHeight = document.body.offsetWidth * img.height / img.width;
    document.body.style.height = bgHeight + 'px';
}
window.onresize = resize; resize();

JS , jsPerf.

+12

( ):

<!-- CSS -->
    <style>
        div.img { 
            background-repeat: no-repeat;
            background-position: center center;
            -webkit-background-size: cover;
            -moz-background-size: cover;
            -o-background-size: cover;
            background-size: cover;
        }
        div.img:nth-of-type(1) {background-image: url('img.jpg');}
        div.img:nth-of-type(2) {background-image: url('img.jpg'); 
        }
    </style>

    <!-- HTML -->
    <div class-"img"></div>
    <div class-"img"></div>
+1

All Articles