如何解决实现 HTML <picture> 标签以启用 WEBP 支持,如何正确处理 max-width
我有兴趣切换到 HTML
test.jpg 和 test.webp 都是 640x480
原始代码(无
<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(640×480 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>
结果:这在现代浏览器中似乎表现正确,但我担心在不支持
我还尝试在图片标签和/或 img 标签中添加“width=640px”,但似乎没有太大区别。
解决方法
这是我找到的最佳解决方案:
-
将标签的最大宽度设置为 90%(或任何你想要的)
-
将标签的宽度设置为图像的实际大小,除非您希望它始终被缩放
-
将图片标签的最大宽度设置为 100%
-
将图片标签的宽度设置为等于或大于img标签宽度除以max-width的数字。比如img tag width = 640 max-width = 90%,640/0.9 = 711.111...,我把图片tag的宽度设置为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>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。