Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying both image size and pixel density in srcset

Here's my img tag:

<img src="https://myserver.com/image?w=667&h=375 667w" 
  srcset="https://myserver.com/image?w=1366&h=1024 1366w 1x,
  https://myserver.com/image?w=1366&h=1024&dpr=2 1366w 2x,
  https://myserver.com/image?w=1366&h=1024&dpr=3 1366w 3x,
  https://myserver.com/image?w=1024&h=768 1024w 1x,
  https://myserver.com/image?w=1024&h=768&dpr=2 1024w 2x,
  https://myserver.com/image?w=1024&h=768&dpr=3 1024w 3x,
  https://myserver.com/image?w=800&h=480 800w 1x,
  https://myserver.com/image?w=800&h=480&dpr=2 800w 2x,
  https://myserver.com/image?w=800&h=480&dpr=3 800w 3x" sizes="100%">

I'm using imgix which returns the image in correct pixel density based upon the dpr query parameter. The above does not seem to work, the image is not rendered in the right size. Am I not using the correct format?

like image 673
Sammy Avatar asked Oct 22 '25 13:10

Sammy


1 Answers

You can't mix the x and w descriptors in your srcset attribute.

I don't know imgix, but I suppose ?w=800&h=480&dpr=2 returns an image with dimensions of 1600x960 pixels. Are https://myserver.com/image?w=800&h=480&dpr=2 and https://myserver.com/image?w=1600&h=960&dpr=1 the same image?

If the image is always the same (same content and same aspect ratio) on every visible size, you should define which visible/CSS sizes you need (depends on your design, for example 800, 1200 and 1600 pixels) and write this:

<img
  src="https://myserver.com/image?w=800&h=400"
  srcset="https://myserver.com/image?w=800&h=400 800w,
    https://myserver.com/image?w=1200&h=600 1200w,
    https://myserver.com/image?w=1600&h=800 1600w,
    https://myserver.com/image?w=2000&h=1000 2000w,
    https://myserver.com/image?w=2400&h=1200 2400w,
    https://myserver.com/image?w=2800&h=1400 2800w,
    https://myserver.com/image?w=3200&h=1600 3200w"
  sizes="100vw">

The ?w=2400&h=1200 image will be downloaded by the browser for several configurations:

  • screen density 1 with viewport width equal to or below 2400px
  • screen density 2 with viewport width equal to or below 1200px
  • screen density 3 with viewport width equal to or below 800px
  • etc.
like image 185
Nicolas Hoizey Avatar answered Oct 26 '25 07:10

Nicolas Hoizey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!