attila.polakovics
attila.polakovics

Reputation: 43

Defining srcset without original size

Is there a way to add scrset to an image without specifying the original width in the sizes attribute?

For example, I have this image:

<img src="image.png" srcset="image_XXS.png 320w, image_XS.png 480w, image.png 481w" sizes="100vw">

The original size is 555px. It uses the original image on viewports wider than 480px, as expected, but stretches it above 555px. I found out that if I add the original width to the sizes attribute

<img src="image.png" srcset="image_XXS.png 320w, image_XS.png 480w, image.png 481w" sizes="(min-width: 555px) 555px, 100vw">

or wrap it in a div with a fixed width, it works.

Can I do it without knowing the original size?

Thanks in advance!

Upvotes: 4

Views: 2425

Answers (1)

rmartrenado
rmartrenado

Reputation: 1576

As far as I know, you have to use the Picture element for this purpose. I have been in the same crossroad now knowing what to do with unknown images sizes.

What I have, like you, is three versions of the same image, resized to half and then another half, so I would like to use them depending on screen size, that's it.

Go for this:

<picture>
  <source media='(min-width: 1200px)' srcset='large.jpg'>
  <source media='(min-width: 768px)' srcset='medium.jpg'>
  <img src='small.jpg' alt='alternative text' />
</picture>

It has the same support as img srcset:

https://caniuse.com/#search=picture

Upvotes: 3

Related Questions