Can I use `<img srcset>` or `<picture>` for image size rather than viewport size?

孤者浪人 提交于 2019-12-06 12:46:49

As was mentioned in the comments, this doesn't exist yet.
However, I've been thinking. If you don't mind a little trickery, there's a workaround.
We can use an iframe.

To the contents of an iframe, its width is the viewport. So then we can use the standard srcset tricks.

Let's say our img looks like this

<img src="https://placehold.it/200x100" alt=""
  srcset="https://placehold.it/200x100 200w, https://placehold.it/500x250 500w">

using the 200x100 image at smaller resolutions (200px or less) and the 500x250 one at higher resolutions.
We can then put this in a HTML file with a zero margin around it, because the iframe expects an actual HTML document.

Now to avoid having to load multiple files, we can turn this into a data URL, which will look as follows:

data:text/html;charset=utf-8,%3Cbody style='margin%3A0'%3E%3Cimg src='https%3A//placehold.it/200x100' srcset='https%3A//placehold.it/200x100 200w, https%3A//placehold.it/500x250 500w

and all that will make our original HTML page look something like this.
Note that, to show it works, I included two iframes, which are identical in themselves. Only their CSS widths differ.

iframe {width:200px; height:100px}
iframe ~ iframe {width:400px; height:200px}
<iframe src="data:text/html;charset=utf-8,%3Cbody style='margin%3A0'%3E%3Cimg src='https%3A//placehold.it/200x100' srcset='https%3A//placehold.it/200x100 200w, https%3A//placehold.it/500x250 500w' alt=''%3E" frameborder="0">?</iframe>
<br><br>
<iframe src="data:text/html;charset=utf-8,%3Cbody style='margin%3A0'%3E%3Cimg src='https%3A//placehold.it/200x100' srcset='https%3A//placehold.it/200x100 200w, https%3A//placehold.it/500x250 500w' alt=''%3E" frameborder="0">?</iframe>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!