我可以使用<图片>吗?对于高度和宽度受限的图像? [英] Can I use &lt;picture&gt; for both height and width-constrained images?

查看:21
本文介绍了我可以使用<图片>吗?对于高度和宽度受限的图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个幻灯片,其中图像会尽可能大地展开,但不会超过视口的宽度或高度.基本上object-fit:包含.

我想让这些图像具有响应性,因为手机和大型桌面的尽可能大"是完全不同的.我不能使用 <img srcset> 因为现在,它只使用屏幕密度(x 描述符)或宽度(w 描述符).这样就让 自己手动制作选择逻辑.

我开始于:

<图片><源媒体=(方向:肖像)"尺寸=(最大宽度:1200像素)100vw,1200像素"srcset="300.jpg 300w, 500.jpg 500w, 800.jpg 800w, 1200.jpg 1200w"><源尺寸=(最大宽度:1200像素)100vw,1200像素"srcset="300.jpg 300w, 500.jpg 500w, 800.jpg 800w, 1200.jpg 1200w"><img src="default.jpg" alt="一个人在香蕉皮上滑倒了"></图片>

但这并不像屏幕方向那么简单,因为所涉及的实际纵横比可能会变得非常奇特,无论是对于视口(非常高的手机、浏览器工具栏等)还是对于图像本身;同一图像可能在一个屏幕上受宽度限制,但在另一个屏幕上受高度限制.我想我可以编写一个脚本来解析纵横比,但我很难将其转换为有意义的 srcsetsizes 列表.

理想情况下 将 .

I have a slideshow sort of thing where images will expand as large as they can, but not exceed the viewport's width or height. Basically object-fit: contain.

I'd like to make these images responsive, since "as large as they can" for a phone and a great big desktop is quite the difference. I can't use <img srcset> because right now, it only does screen density (x descriptors) or width (w descriptors). So that leaves <picture> to manually make the selection logic myself.

I started with:

<picture>
  <source media="(orientation:portrait)"
          sizes="(max-width: 1200px) 100vw, 1200px"
          srcset="300.jpg 300w, 500.jpg 500w, 800.jpg 800w, 1200.jpg 1200w">
  <source sizes="(max-width: 1200px) 100vw, 1200px"
          srcset="300.jpg 300w, 500.jpg 500w, 800.jpg 800w, 1200.jpg 1200w">
  <img src="default.jpg" alt="a man slipping on a banana peel">
</picture>

But it's not as simple as the screen's orientation, since the actual aspect ratios involved can get pretty exotic, both for viewports (very tall phones, browser toolbars, etc.) and for the images themselves; the same image might be width-constrained on one screen, but height-constrained on another. I figure I can write a script that parses out the aspect ratios, but I'm stumped on the logic to turn that into a meaningful srcset and sizes list.

Ideally <img srcset> will get the h descriptor soon, but I'd like to hack something together that will work now.

解决方案

I think I got it (1/2) is equal to (width/height):

<img 
    srcset="http://lorempixel.com/960/1920/sports/10/w1920/ 960w"
    sizes="(min-aspect-ratio: 1/2) calc(100vh * (1 / 2))"
    />

Or with more code:

<img
    srcset="http://lorempixel.com/960/1920/sports/10/w1920/ 960w"
    sizes="(min-aspect-ratio: 1/2) calc(100vh * (1 / 2)), 100vw"
    />


As a side note: I also have written a script that automatically calculates the right sizes for parent height/width constrained sizes. See here the parent-fit script.

这篇关于我可以使用<图片>吗?对于高度和宽度受限的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆