HTML & CSS Interview Question #119
What is aspect-ratio in CSS?
Responsive Design, Modern CSS, Variables, Transitions & Animations Senior Advanced
Quick Interview Answer
The aspect-ratio property defines a preferred width-to-height ratio for an element. It is useful for reserving predictable media space, creating video frames, maintaining card thumbnails, and reducing layout shifts.
Detailed Explanation
The aspect-ratio property defines a preferred width-to-height ratio for an element. It is useful for reserving predictable media space, creating video frames, maintaining card thumbnails, and reducing layout shifts.
It works with the sizing algorithm rather than simply forcing both dimensions in every situation. A common pattern combines width: 100% with an aspect ratio and object-fit for media.
Code Example
.video-frame {
width: 100%;
aspect-ratio: 16 / 9;
}
.product-image {
width: 100%;
aspect-ratio: 4 / 3;
object-fit: cover;
}