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.
The height and width of an image can be set using height and width attribute. The height and width can be set in terms of pixels. The <img> height attribute is used to set the height of the image in pixels. The <img> width attribute is used to set the width of the image in pixels.
Image size equals the dimensions of an image. You can measure image dimensions in any unit, but you'll typically see pixels used for web or digital images, and inches used for print images. It's important to note that two different images that have the same aspect ratio may not have the same image size or dimensions.
Web performance advocates have often advised to add dimensions to your images for best performance to allow the page to be laid out with the appropriate space for the image, before the image itself has been downloaded.
If width and height are not specified, the page will flicker while the image loads.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With