0

I have a dynamic JS code that changes the background image of div on each click. How can I change div height and width dependent on the image size?

Here is my code for better understanding my problem:

element.style {
    background: rgba(0, 0, 0, 0) url("../wp-content/uploads/ssf-wp-uploads/images/24/image.jpg") no-repeat scroll center center;
    cursor: pointer;
    height: 150px;
    position: relative;
}

Here I set a fix size 150px but background image size can change. So I want to set div height depending on background image height .

Filthy_Rich
  • 666
  • 5
  • 20

2 Answers2

1

Since you have mentioned that you want to get div height to auto-adjust to background image, Note that, A background image has no effect on the size of the div it is declared in.

div{
    background-image: url('http://www.pets4homes.co.uk/images/articles/1111/large/feline-influenza-all-about-cat-flu-5239fffd61ddf.jpg');
    background-size: contain;
    background-repeat: no-repeat;
    width: 100%;
    padding-top: 66.64%; /* (img-height / img-width * container-width) */
                /* (853 / 1280 * 100) */
}

This is a trick to make a background image work like a img. For a better understanding on how the size of the image should be known before hand, I recommend reading the author's answer in detail along with the comments here: How to get div height to auto-adjust to background size?

Community
  • 1
  • 1
DirtyBit
  • 16,613
  • 4
  • 34
  • 55
0

CSS

.elementstyle{
        background-image: url('http://www.pets4homes.co.uk/images/articles/1111/large/feline-influenza-all-about-cat-flu-5239fffd61ddf.jpg');
        background-size: contain;
        background-repeat: no-repeat;
        background-size: contain;

}

In jQuery:

var img= $('img');

img.removeAttr("width");
img.removeAttr("height");

var img_width = img.width();
var img_height = img.height();

$('.elementstyle').width(img_width).height(img_height);

Edit: I've just noticed that you're asking to get the size of the background image from the CSS. The method above would grab attributes from:

<div class="elementstyle"><img src=""/></div>

You'll have to look into defining the size of the background-image within jQuery. Here's some reading material.

Community
  • 1
  • 1
Filthy_Rich
  • 666
  • 5
  • 20