HTML & CSS
/Intermediate
aspect-ratio
Definition
A CSS property that sets a preferred aspect ratio for the box, which will be used in the calculation of auto sizes.
Explain Like I'm New
If you want a box to always be a perfect square, you used to have to write complex JavaScript or CSS padding hacks. Now, you just write `aspect-ratio: 1 / 1;`. If the width is 500px, the browser automatically forces the height to be 500px.
Real World Example
Embedding a YouTube video. You want it to be responsive, but it MUST stay in the classic 16:9 widescreen movie format, or else you get ugly black bars. `aspect-ratio: 16 / 9;` solves it instantly.
Common Use Cases
- •Responsive video embeds
- •Perfectly square profile pictures
- •Image grids
Interactive Example
Interview Questions
basic
- What value makes an element a perfect square?
intermediate
- If I set `width: 100%;` and `aspect-ratio: 16 / 9`, do I need to set the `height`?