Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

html - CSS custom properties (variables) in <picture> <source> sizes

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?

question from:https://stackoverflow.com/questions/65950066/css-custom-properties-variables-in-picture-source-sizes

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...