Fit div size to background image

Berna picture Berna · May 19, 2015 · Viewed 25.2k times · Source

I'm trying to set the size (both width and height) of a div to match it's background image size, but I can't get it working. The background image size has to be in percentages, because I'm dealing with a responsive website. On smaller screens, the background should be displayed completely (with less width, but still proportional), and the div who has the image should follow that size.

I tried various values of the background-size, such as auto 100%, cover, contain, etc. but nothing did the trick. There's a similar question here about this: scale div to background image size but it didn't solve my problem either.

I'd really appreciate if someone knows how to do it.

EDIT: I made a fiddle to show the behavior: http://jsfiddle.net/osv1v9re/5/ This line is what is making the background image so small:

background-size: auto 100%;

But if it is removed is removed, the background will fill the proper width, but not the height.

Answer

Heah picture Heah · May 27, 2015

tag cannot adapt to background-image size, you need to use an tag and choose between height: auto for the div or javascript

// **** Problem ****

// Wrong html :
<div class="my_class"><div>

// with css :
.my_class {
    width: 100%;
    height: 100%;
    background-image: url(/images/my-image.jpg);
    background-size: 100%;
    background-position: center;
    background-repeat: no-repeat;
}

//****  Solution ****

// use css:
.my_class {
    width: 100%;
    height: 100%;
    background-image: url(/images/my-image.jpg);
    background-size: contain;
}