WeekendCoder
WeekendCoder

Reputation: 1033

Using srcset for different device sizes AND resolutions

i'm using this for the mobile version (media query) of my new page:

<!-- CSS is img{width=100%;height:auto} -->
<img src="360x1.jpg" srcset="360x1.jpg 1x, 360x2.jpg 2x, 360x3.jpg 3x">

Works fine so far on mobile phones and also with DPR ones...

So now the next step would be adding tablets (768px).

I thought it should be possible this way:

<img src="360x1.jpg" srcset="360x1.jpg 1x, 360x2.jpg 2x, 360x3.jpg 3x, 768x1.jpg 1x 768w, 768x2.jpg 2x 768w, 768x3.jpg 3x 768w">

So this would combine DPR and the device width. Would. :-)

I know the picture-tag but i'm not sure if this is the right solution. Also i know the sizes-attribute but...

Any idea how to solve this? Thanks!

Upvotes: 1

Views: 708

Answers (1)

benvc
benvc

Reputation: 15130

From the attribute descriptions for <img>:

It is incorrect to mix width descriptors and pixel density descriptors in the same srcset attribute.

Also, regarding using the sizes attribute with pixel density descriptors:

If the srcset attribute is absent, or contains no values with a width (w) descriptor, then the sizes attribute has no effect.

Instead of <img>, you could use <picture> with a source and corresponding media attribute for each device size including pixel density descriptors in the srcset attribute.

<picture> 
   <source srcset="https://via.placeholder.com/50x50 1x,
                   https://via.placeholder.com/100x100 2x"
           media="(max-width: 767px)">
   <source srcset="https://via.placeholder.com/200x200 1x,
                   https://via.placeholder.com/400x400 2x">
   <img src="https://via.placeholder.com/100x100" alt="picture"> 
</picture>

Upvotes: 3

Related Questions