0
votes

I'm using a different img srcset depending on the width. This is my code:

<img id="portadaImg" class="img-fluid"
                 srcset="images/portada/portada-xl.jpg 2400w,
                         images/portada/portada-l.jpg 1200w,
                         images/portada/portada-md.jpg 992w,
                         images/portada/portada-tablet.jpg 768w,
                         images/portada/portada-mobile.jpg 458w"
                 src="images/portada/portada-mobile.jpg"
                 alt="Foto de portada"/>

The problem is that for mobiles (<480w) I have a different image than for the rest of the devices (it has more height than width). It works propertly for mobiles which don't have a retina screen, but for those ones as the width is taken 2x their original width srcset considers that it's more suitable the 992w image, which is not supposed to be loaded on a phone. I want to know if there is a way to declare the srcset that always take the 458w image for devices under that width, no matter if they have retina screen or not, only attending the real width dimensions of the device.

I want that the image displayed depends on the real width of the screen, this means that the imagen displayed for a non retina screen device with 380px width is the same as the displayed for a retina screen device with 380px width. I need to do this with image tag and srcset, I cant do it with a div with a img-background and media queries.

1
@dippas Its not the same question, look the capital letters on the edit.Luiscri

1 Answers

0
votes

This would be achievable with sizes, the sibling attribute of srcset:

<img id="portadaImg" class="img-fluid"
                 srcset="images/portada/portada-xl.jpg 2400w,
                         images/portada/portada-l.jpg 1200w,
                         images/portada/portada-md.jpg 992w,
                         images/portada/portada-tablet.jpg 768w,
                         images/portada/portada-mobile.jpg 458w"
                 sizes="(max-width: 480px) 480px
                        (max-width: 768px) 768px
                        (max-width: 992px) 992px
                        (max-width: 1400px) 1400px
                        2400px"
                 src="images/portada/portada-mobile.jpg"
                 alt="Foto de portada"/>

More information is available at MDN. In short, it will check the size specified in the first matched media query in sizes and will choose the most appropriate image source from srcset.