Getting the height of a background image resized using “background-size: contain”
So I have an image gallery. Each image is a
background-image that stretches across the entire page.
To ensure that every image uses the maximum available width, I give it the following background-size:
background-size: 100% auto;
However, some of the images are taller than the available screen height.
To make sure the image is visible in full (at least using scroll bars), I would need to give the
body element the height of the resized background image.
Is this true? Do I have to resort to normal image elements after all?
There are many approaches to getting the size of a static background image, like How do I get background image size in jQuery? but they obviously don’t apply here.
The key is to use the static image’s dimensions, calculate the aspect ratio of the image, and then use the actual element’s dimensions to figure out the computed dimensions of the resized image.
For instance, lets assume you had the following:
The static image’s dimensions are
50x100, and it is sized to take up a width of
100% of the body element. Therefore the
body element’s width would be equal to the resized image’s width. If you wanted to calculate the resized height of the image, you would just use the image’s aspect ratio. In this case, the image’s resized height would be
(400*100)/50 = 800
Pure JS approach: EXAMPLE HERE
The pure JS method is going to be the fastest, as demonstrated by this jsPerf example.