Years and years we have used padding hack for responsive videos and iframes. But now we can use aspect-ratio property.
The aspect-ratio
property allows you to set the aspect ratio of an element directly. Here’s an example code to set an aspect ratio of 16:9 for an iframe using the aspect-ratio
property:
.iframe-wrapper {
aspect-ratio: 16/9; /* 16:9 aspect ratio */
}
.iframe-wrapper iframe {
width: 100%;
height: 100%;
}
In the above code, the aspect-ratio
property is set to 16/9
, which sets the aspect ratio of the wrapper element to 16:9. The iframe is set to width: 100%
and height: 100%
to fill the available space in the wrapper element.
That’s it! Here is demo about aspect-ratio.
Similar logic can be applied to images also. Let’s say you have a “card” component where you want image to always be 1:1. Even though original images proportions might vary.
.image-wrapper {
aspect-ratio: 1/1; /* 1:1 aspect ratio */
}
.image-wrapper img {
width: 100%;
height: 100%;
object-fit: cover;
}
In the above code, the aspect-ratio
property is set to 1/1
, which sets the aspect ratio of the wrapper element to 1:1. The image is set to width: 100%
and height: 100%
to fill the available space in the wrapper element, and the object-fit
property is set to cover
to ensure the image completely covers the wrapper element while maintaining its aspect ratio.