【问题标题】:Implementing HTML <picture> tags to enable WEBP support, how to handle max-width properly实现 HTML <picture> 标签以启用 WEBP 支持,如何正确处理 max-width
【发布时间】:2021-07-06 12:15:32
【问题描述】:

我有兴趣切换到 HTML 标签以同时支持 WEBP 和 JPEG,但是,我遇到了关于 max-width 属性的令人困惑的行为。

test.jpg 和 test.webp 都是 640x480

原码(无标签,无WEBP):

<img src="test.jpg" style="max-width:80%">

结果:一切正常,图像呈现为 640x480 或缩小浏览器宽度时缩小

错误代码 #1:

<picture>
    <source srcset="test.webp" type="image/webp">
    <source srcset="test.jpg" type="image/jpeg">
    <img src="test.jpg" style="max-width:80%">
</picture>

结果:即使浏览器宽度不受限制,图像也会缩小到 512x384(640x480 的 80%)

错误代码 #2:

<picture style="max-width:80%">
    <source srcset="test.webp" type="image/webp">
    <source srcset="test.jpg" type="image/jpeg">
    <img src="test.jpg" style="">
</picture>

结果:图像以正确的大小呈现,但如果浏览器窗口缩小,图像不会按比例缩小

错误代码 #3:

<picture style="max-width:80%">
    <source srcset="test.webp" type="image/webp">
    <source srcset="test.jpg" type="image/jpeg">
    <img src="test.jpg" style="max-width:80%">
</picture>

结果:与 #1 相同(图像渲染为 512x384 而不是 640x480)

体面的代码:

<picture style="max-width:80%">
    <source srcset="test.webp" type="image/webp">
    <source srcset="test.jpg" type="image/jpeg">
    <img src="test.jpg" style="max-width:100%">
</picture>

结果:这似乎在现代浏览器中表现正确,但我担心在不支持 标签的旧浏览器中,图像将缩小到 100% 而不是 80%

我也尝试将“width=640px”添加到图片标签和/或img标签,但似乎没有太大区别。

【问题讨论】:

    标签: html css image width webp


    【解决方案1】:

    这是我找到的最佳解决方案:

    1. 将标签的最大宽度设置为 90%(或任何你想要的)

    2. 将标签上的宽度设置为图像的实际大小,除非您希望它始终被缩放

    3. 设置图片标签的最大宽度为100%

    4. 将图片标签的宽度设置为等于或大于img标签宽度除以max-width的数字。比如img标签width = 640 max-width = 90%, 640/0.9 = 711.111...,我把图片标签的宽度设置为720只是为了使用更偶的数,没关系只要是更大

    <picture style="max-width:100%;width:720px">
        <source srcset="test.webp" type="image/webp">
        <source srcset="test.jpg" type="image/jpeg">
        <img src="test.jpg" style="max-width:90%;width:640px">
    </picture>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-12
      • 1970-01-01
      • 2011-08-09
      • 2017-12-12
      • 2012-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多