Is it possible to make a responsive div with a background-image that maintains the ratio of the background-image like with an <img>?

Here is a nice and simple tip with only css/html:

Ingredients

  • Transparent PNG image with the desired ratio (transparent-ratio-conserver.png)

  • tag

  • Different images for different view-ports (retina.jpg, desktop.jpg, tablet.jpg...)

The idea is to open an tag and to assign to it a transparent image (with our desired ratio). We also add class="responsive-image" that's all in HTML.

<img src="img/transparent-ratio-conserver.png" class="responsive-image">

In the CSS, we set background-size to fit the and we choose the width of our image.

.responsive-image{
    width: 100%;
    background-size: 100% 100%;
} 

and finally, we serve for every view-port the right image:

/* Retina display */
@media screen and (min-width: 1024px){
    .responsive-image{
        background-image: url('../img/retina.jpg');
    }
}
/* Desktop */
@media screen and (min-width: 980px) and (max-width: 1024px){
    .responsive-image{
        background-image: url('../img/desktop.jpg');
    }
}
/* Tablet */
@media screen and (min-width: 760px) and (max-width: 980px){
    .responsive-image{
        background-image: url('../img/tablet.jpg');
    }
}
/* Mobile HD */
@media screen and (min-width: 350px) and (max-width: 760px){
    .responsive-image{
        background-image: url('../img/mobile-hd.jpg');
    }
}
/* Mobile LD */
@media screen and (max-width: 350px){
    .responsive-image{
        background-image: url('../img/mobile-ld.jpg');
    }
} 

You can download the demo from here.


This is done with the background-size property:

background-size: cover;

Cover will make the image as small as it can be, whilst still covering the entirety of its parent, and maintaining its aspect ratio.

You may also want to try contain, which makes the image as big as it can be whilst still fitting inside the parent.

Source(s)

MDN - background-size CSS property


I think theres a better solution than contain or cover (which dind't work for me, btw). Here's an example I recently used for a logo:

#logo{
    max-width: 600px;
    min-height: 250px;
    margin: 0 auto;
    background: url(../images/logo.png) no-repeat center;
    background-size: 100%;
}

So now we have a responsive div with a backgound image, which size is set to the full width of the div.