CSS aspect-ratio
Maintain perfect proportions in responsive layouts
What is aspect-ratio in CSS?
The aspect-ratio property in CSS allows you to define the width-to-height ratio of an element, ensuring it maintains its proportions regardless of the content or screen size. This is especially useful for responsive images, videos, cards, and any UI component that needs to scale predictably.
- Syntax:
aspect-ratio: <width> / <height>; - Example:
aspect-ratio: 16 / 9;(width is always 16 units for every 9 units of height) - Applies to: All elements except inline boxes and non-replaced inline elements.
- Overrides: If both
widthandheightare set,aspect-ratiois ignored.
Why use it? Before aspect-ratio, developers used padding hacks or JavaScript to maintain proportions. Now, it's a single, clean CSS property!
Interactive Examples
1:1 Square
.aspect-square {
aspect-ratio: 1 / 1;
background: #4f8cff;
}
16:9 Video Frame
.aspect-video {
aspect-ratio: 16 / 9;
background: #222 url('../images/fireman.webp') center/cover;
}
3:4 Portrait
.aspect-portrait {
aspect-ratio: 3 / 4;
background: linear-gradient(135deg, #ffb347, #ffcc33);
}
Aspect Ratio Playground
Change the aspect ratio values below to see the box update in real time!
.playground-demo {
aspect-ratio: 4 / 3;
background: repeating-linear-gradient(135deg, #4f8cff 0 10px, #fff 10px 20px);
}