Auto-width image with `srcset` attribute
Asked Answered
S

1

5

Say I have the following image:

<img src="//picsum.photos/100" srcset="//picsum.photos/100 100w">

It appears that the sizes attribute I have not included defaults to 100vw, hence the small image is upscaled to the width of the viewport.

What do I do if I don't want this behavior, but instead want the image to default to its intrinsic size?

I would expect that this image would default to 100px in width on a normal display, and 50px on a 2x (retina) display.

If I specify my own sizes attribute of 100px, this doesn't solve the problem of displaying it at 50px when on a retina display.

The reason I need this behavior is because in my system users are allowed to upload images of any size and place them on a page, and I am generating an srcset with multiple steps up to the max size of their image, and I need a way for the image to display at the correct width given the size of the image and the pixel density of the user's screen.

Can this behavior for auto-width images be achieved using srcset?

In my research I've found this article which addresses the issue directly. The author recommends adding the width attribute with the maximum size of the image to revert what the sizes attribute does to the image's intrinsic size. However, he does not address how to make this work with differing pixel densities.

Surrealism answered 10/12, 2018 at 18:57 Comment(0)
S
6

Unfortunately it seems there isn't a way to have an image with srcset default to its natural size, taking DPR into account. The sizes attribute, which defaults to 100vw if not set on an image with srcset, redefines the image's intrinsic width, and there doesn't seem to be a way to reset it without providing an explicit width yourself.

In my specific situation I discovered that we were already storing the user's DPR in a cookie, so server-side I've started setting the width attribute on images to the max width of the image divided by the user's DPR. This prevents the image from being displayed larger than the original size, and ensures that the image is sized appropriately for devices with high pixel densities.

Of course, you'll probably want to combine this with max-width: 100%; in your CSS to prevent the image from displaying larger than its container.

Example solution:

<!-- Width generated server-side for standard displays: -->
<img src="//picsum.photos/100" srcset="//picsum.photos/100 100w" width=100>

<!-- Width generated server-side for displays with a DPR of 2: -->
<img src="//picsum.photos/100" srcset="//picsum.photos/100 100w" width=50>
Surrealism answered 11/12, 2018 at 12:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.