Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve computed value from background-size:cover/contain

Tags:

javascript

css

Covering the browser's viewport with a 400x200 background image using background-size:cover:

html, body {height:100%;} body {background:url("http://lorempixel.com/g/400/200/") center no-repeat; background-size:cover;} 

I'd like to retrieve - through javascript - the computed background-size value that is applied to the picture, for example 1536px 768px

Live demo : http://s.codepen.io/abernier/fullpage/rHkEv

NB: I just want to read it, at no time compute it (since the browser already has, in a way)

like image 792
abernier Avatar asked Jan 19 '14 11:01

abernier


People also ask

What does background-size cover do?

The background-size CSS property sets the size of the element's background image. The image can be left to its natural size, stretched, or constrained to fit the available space.

Can we specify the background-size in percentages?

When we set background-size: 113% , it means the the width can be max 113% of the container's width, which would be, 63.28px and this is roughly 50% of the original image's width.

Can we specify the background-size in percentage in CSS?

If you only provide one value (e.g. background-size: 400px ) it counts for the width, and the height is set to auto . You can use any CSS size units you like, including pixels, percentages, ems, viewport units, etc.


1 Answers

I know I'm very late to the party but i have used the code below to solve this.

    var backgroundImage = new Image();     backgroundImage.src = $('my_div_id').css('background-image').replace(/"/g,"").replace(/url\(|\)$/ig, "");      backgroundImage.onload = function() {         var width = this.width;         var height = this.height;          var object = $('#my_div_id');          /* Step 1 - Get the ratio of the div + the image */         var imageRatio = width/height;         var coverRatio = object.outerWidth()/object.outerHeight();          /* Step 2 - Work out which ratio is greater */         if (imageRatio >= coverRatio) {             /* The Height is our constant */             var coverHeight = object.outerHeight();             var scale = (coverHeight / height);             var coverWidth = width * scale;         } else {             /* The Width is our constant */             var coverWidth = object.outerWidth();             var scale = (coverWidth / width);             var coverHeight = height * scale;         }         var cover = coverWidth + 'px ' + coverHeight + 'px';         alert('scale: ' + scale + ', width: ' + coverWidth + ', height: ' + coverHeight + ', cover property: ' + cover);     }; 

A detailed walkthrough can be found here http://www.gene.co.uk/get-computed-dimensions-background-image-background-size-cover/

like image 190
Hob Avatar answered Oct 14 '22 11:10

Hob