The aspect-ratio property in CSS is used to maintain a fixed width-to-height ratio for elements.
It helps elements resize proportionally without manually setting both width and height.
This is especially useful for:
- Images
- Videos
- Cards
- Responsive layouts
- Embeds and iframes
- Gallery items
Why aspect-ratio is Important
Before aspect-ratio, developers often used:
[code theme="dark"]
padding-top hacks
[/code]
to maintain responsive ratios.
Now modern CSS provides a cleaner and simpler solution.
Basic Syntax
[code theme="dark"]
.element{
aspect-ratio:16 / 9;
}
[/code]
This creates a:
- 16 units width
- 9 units height
Simple Example
[code theme="dark"]
.box{
width:300px;
aspect-ratio:1 / 1;
background:#dbeafe;
}
[/code]
This creates a perfect square.
[grid]
16:9 Video Ratio Example
Square Card Layout
Responsive Image Gallery
Modern Aspect Ratio Demo
[/grid]
Common Aspect Ratios
|
Ratio
|
Common Use
|
|
1 / 1
|
Square images
|
|
16 / 9
|
Videos and banners
|
|
4 / 3
|
Traditional screens
|
|
21 / 9
|
Ultrawide layouts
|
Responsive Video Example
[code theme="dark"]
.video{
width:100%;
aspect-ratio:16 / 9;
}
[/code]
The video automatically keeps its ratio on all screen sizes.
Image Card Example
[code theme="dark"]
.card-image{
aspect-ratio:4 / 3;
overflow:hidden;
}
.card-image img{
width:100%;
height:100%;
object-fit:cover;
}
[/code]
Useful for responsive image galleries and cards.
aspect-ratio with Flexbox and Grid
Works perfectly with:
- Flexbox layouts
- CSS Grid layouts
- Responsive cards
- Gallery systems
[code theme="dark"]
.grid{
display:grid;
grid-template-columns:repeat(3,1fr);
gap:20px;
}
.item{
aspect-ratio:1 / 1;
}
[/code]
aspect-ratio vs Old Padding Hack
|
Method
|
Complexity
|
Modern Support
|
|
Padding Hack
|
Complex
|
Older Technique
|
|
aspect-ratio
|
Simple
|
Modern CSS
|
Advantages of aspect-ratio
- Cleaner responsive layouts
- No padding hacks required
- Easy proportional sizing
- Better maintainability
- Perfect for media layouts
- Works with Grid and Flexbox
Disadvantages of aspect-ratio
- Older browsers may not support it
- Requires understanding responsive sizing
- Some layouts may still need explicit height control
Best Use Cases
- Responsive videos
- Image galleries
- Cards and thumbnails
- Embedded content
- Hero banners
- Modern dashboard layouts
Cross Browser Compatibility
- Chrome → Supported
- Edge → Supported
- Firefox → Supported
- Safari → Supported
- Mobile Browsers → Good Support
Modern browsers support aspect-ratio very well.
It is now considered one of the most important modern responsive CSS features.
Browser Support Summary
[code theme="dark"]
.card{
aspect-ratio:16 / 9;
}
[/code]
is considered a clean and modern CSS solution for maintaining responsive proportional layouts.