7

I'm trying to best describe to the browser which image to pick from a srcset list using the sizes attribute.

Basic is:

<picture>
  <source 
    type="image/jpeg" 
    media="(min-width: 1024px)" 
    srcset="a.jpg 1024w, b.jpg 1200w, c.jpg 2048w, d.jpg 2400w" 
    sizes="100vw"
  >
  <img src="e.jpg">
</picture>

Now you might have a "max viewport" at which point your webpage "stops growing", so you add a media query in your sizes:

<source
  ...
  sizes="(min-width: 1200px) 1200px, 100vw"
>

Your image might also have some padding, so you might be tempted to use 98vw instead of 100vw but that's not always accurate if the paddings are in pixels for example, so what you can do instead it use calc:

<source
  ...
  sizes="(min-width: 1200px) 1200px, calc(100vw - 20px)"
>

So far we've only been using absolute units, but I've read you can also use context-dependent units like em:

<source
  ...
  sizes="(min-width: 1200px) 1200px, calc(100vw - 2em)"
>

Interestingly, that means the browser must be aware of the styles being applied to the image (since em can change based on CSS). So if this is true, could you use CSS custom properties (or "CSS variables") in your sizes?

<source
  ...
  sizes="(min-width: 1200px) 1200px, calc(var(--six-columns) - var(--image-padding))"
>

Thanks!


As a bonus question: any idea where I could find the browser support for such a thing?

1 Answer 1

4

The answer to this is NO!

When using em as a unit inside the sizes attribute, the browser will use a fixed predetermined size (14px in chrome apparently, determined experimentally).

In the end, no information actually comes from CSS, and CSS custom properties aren't actually usable that way.

Sign up to request clarification or add additional context in comments.

2 Comments

use em there is like using em inside media query: stackoverflow.com/a/23614634/8620333
Here's a reduced test case to prove that this doesn't work: output.jsbin.com/katigokoja/1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.