CSS

Grace Faires
Grace Faires
5,435 Points

How to create a responsive div with a background image?

Hey,

I've been struggling with this issue for a while, and just wondered if anyone has any advice! Basically I want to place 3 images in a row, that will resize with the browser window. I also want these images to link to another part of the site, and have hover states applied to them, so I can't use img tags.

If I specify height and width in percentages then the image doesn't display because the div collapses... So how else can I make it responsive?

Thank you in advance!

3 Answers

Ryno Botha
PRO
Ryno Botha
Pro Student 4,055 Points

Should work:

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.

Check: https://developer.mozilla.org/en-US/docs/Web/CSS/background-size

To work with Different screen Sizes:

<img src="img.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');
    }
} 

From: http://stackoverflow.com/questions/15883157/is-it-possible-to-make-a-responsive-div-with-a-background-image-that-maintains-t

Hope it helps~ ^^

Grace Faires
Grace Faires
5,435 Points

worked perfectly, thanks!!

Jana Ryndin
Jana Ryndin
7,161 Points

Thank you for this. I was looking for it for while.