Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialGrace Faires
5,435 PointsHow 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
Courses Plus Student 4,055 PointsShould 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');
}
}
Hope it helps~ ^^
Grace Faires
5,435 Pointsworked perfectly, thanks!!
Ryno Botha
Courses Plus Student 4,055 Points^^ any time~
Jana Ryndin
7,161 PointsThank you for this. I was looking for it for while.