Introduction
Maybe you have been faced with the problem of conserving ratio when trying to serve different images for different view-ports, using <div>
tag you cannot conserve ratio, but I have found a solution that will make your life easier.
How Does It Work
Ingredients
- Transparent PNG image with the desired ratio (transparent-ratio-conserver.png)
<IMG>
tag - Different images for different view-ports (retina.jpg, desktop.jpg, tablet.jpg...)
The idea is to open an
<img>
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 <img>
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:
@media screen and (min-width: 1024px){
.responsive-image{
background-image: url('../img/retina.jpg');
}
}
@media screen and (min-width: 980px) and (max-width: 1024px){
.responsive-image{
background-image: url('../img/desktop.jpg');
}
}
@media screen and (min-width: 760px) and (max-width: 980px){
.responsive-image{
background-image: url('../img/tablet.jpg');
}
}
@media screen and (min-width: 350px) and (max-width: 760px){
.responsive-image{
background-image: url('../img/mobile-hd.jpg');
}
}
@media screen and (max-width: 350px){
.responsive-image{
background-image: url('../img/mobile-ld.jpg');
}
}
You can download the demo from here.
Points of Interest
Before that solution, we have to pass with complicated calculation to make <div>
tag conserve certain ratio as described in the article: responsive-background-images-with-fixed-or-fluid-aspect-ratios.
Thank you for sending your feedback.