Thursday, November 21

Aspect Ratio Media Elements and intrinsicsize

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.

The post Aspect Ratio Media Elements and intrinsicsize appeared first on CSS-Tricks.


Source: CSS-tricks.com

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x