views:

21

answers:

1

If I have

background-size: 50% auto;

What if I want to extract the auto value, basically to be able to get the new height or width?

A: 

In CSS3, 'background-size' is relative to the container element. So, '50% auto' will always be exactly half of the width of it's container.

That said, you can get half of the width with jquery like so:

$(function() {
    var w = $('.yourcontainer').width() / 2;
    alert(w);
});

By specifying two values you are defining width and height... You have height set to 'auto', so your image will keep it's original proportions instead of scaling to 50% height. That makes it hard to get the 'height' value without knowing the original proportions of the image. Luckily, you can get those values into javascript pretty easily by creating a new DOM element and testing it's dimensions:

$(function() {

    var img = new Image();
    img.src = 'images/yourimage.jpg';

    var w = $('.yourcontainer').width() / 2;
    var h = (w / img.width) * img.height;

    alert(h);

});
Derek Hunziker