If you need an aspect-ratio sized <div>
(or any element that can have children), you can do it. Perhaps the cleanest way is a custom-property-sized pseudo-element that pushes the correct minimum height through padding-based-on-width.
But media elements like <img>
don’t have children. The <video>
tag isn’t self-closing, but when it is supported (almost always), the content of it is replaced with a shadow DOM you don’t control. Besides, these are the only two elements that “size to an external resource.” So, how do you enforce aspect ratio on them when using a variable width like 100%
or 75vw
? Well, once they load, they will have their natural aspect ratio, so that’s nice. But it also means they don’t know the height while they are loading and it may cause performance jank-ening reflow.
One solution is to put them into a container with an aspect ratio, forcing them to the corners with absolute positioning. But, all by themselves, they are incapable of sizing to the aspect ratio correctly until they load.
Hence, the intrinsicsize
attribute for “all image element types (including SVG images) and videos” that is now under development.
<img intrinsicsize="400x300" style="width: 100%">
The explainer document is helpful. The reason it is intrinsicsize
and not aspectratio
is because an aspect ratio doesn’t provide as much useful or usable information. I’d love to see it work on any element and be brought to CSS as well.
This would be very nice to have; feels like it should have been around for ages already. Was plenty disappointed, though, when I followed the “now under development” link and saw that there’s no public signal of intent to build from any browser vendors besides Chrome. Is there any platform in use these days where developers can vote on new proposed web standards, like IE used to have?
Support is already quite decent, although it should be noted that this feature is in ‘Working Draft’ and could change before becoming part of the living standard. ie. best not to use in production until candidate recommended.
Place to check feature implementation. Note: this is community updated, but it is rather accurate.
https://caniuse.com/#search=intrinsic
This awesome…absolutely can not wait for this to be adopted by the major browsers.
Thanks for sharing…
Pretty sure we’re talking about two different things, no? Your caniuse link is about CSS properties and this post + the link I was referring to (https://www.chromestatus.com/feature/4704436815396864) are about an HTML attribute.
Apologies. We are talking about two different things.
I made a polyfill:
https://github.com/nuxodin/intrinsicsize-polyfill