img srcset - disregard pixel density

3.4k views Asked by At

I have two images, one is 1000 x 800 px ("large"), and one is 200 x 200 px ("small"). I want to use srcset / sizes / picturefill to display the small image when the screen is less than or equal to 500 CSS pixels wide, and the large image otherwise.

Here's a straw-man proposal: http://jsfiddle.net/ghhjfo4z/1/embedded/result/

<img srcset="http://i.imgur.com/hw9O9Ia.jpg 1000w, http://i.imgur.com/BgLoqRx.jpg 500w">

This works fine on my 1x pixel density display. But when I switch over to my 2x pixel density retina display, suddenly the small image is only displayed when the viewport is less than or equal to 250 CSS pixels wide.

Is there any way to make the browser use the small image on my 2x pixel density display when the viewport is less than or equal to 500px?

Basically I want to disregard the pixel density of the device, and use srcset and/or sizes to only choose an image based on CSS pixel width of a viewport.

2

There are 2 answers

1
alexander farkas On BEST ANSWER

In short this is not possible. If you want to have more control you can use the picture element.

<picture>
    <source srcset="img-500w.jpg" media="(max-width: 650px)" />
    <img srcset="img-1000w.jpg" />
</picture>

There is also an interesting lazySizes plugin for you, optimumx. Markup would look like this:

<img
    data-srcset="http://placehold.it/300x150 300w,
        http://placehold.it/700x300 700w,
        http://placehold.it/1400x600 1400w,
        http://placehold.it/2800x1200 2800w"
     data-sizes="auto"
     data-optimumx="1.5"
     class="lazyload"
     src="http://placehold.it/300x150"
     alt="flexible image" />

It would be wise to set it to 1.2 or better 1.5 instead of just 1.

For other performance vs. retina considerations have a look here.

1
René Schubert On

Just for completion: I found the following solution working for me:

<img
    srcset="http://i.imgur.com/hw9O9Ia.jpg 1000w,
        http://i.imgur.com/BgLoqRx.jpg 500w"
    sizes="(-webkit-min-device-pixel-ratio: 2) 50vw,
        (min-resolution: 192dpi) 50vw,
        (min-resolution: 2dppx) 50vw,
        (-webkit-min-device-pixel-ratio: 3) 33.33vw,
        (min-resolution: 288dpi) 33.33vw,
        (min-resolution: 3dppx) 33.33vw" />