How to Use aspect-ratio in CSS: Syntax and Examples
Use the
aspect-ratio property in CSS to set a fixed width-to-height ratio for an element, like aspect-ratio: 16 / 9;. This keeps the element's shape consistent regardless of its size or container.Syntax
The aspect-ratio property accepts a ratio value expressed as width / height. You can use numbers separated by a slash or a single number for a square ratio.
- aspect-ratio: The property name.
- value: The ratio, e.g.,
16 / 9means width is 16 units and height is 9 units.
css
selector {
aspect-ratio: <width> / <height>;
}Example
This example shows a box with a 16:9 aspect ratio. The box width adjusts to the container, and the height changes automatically to keep the ratio.
css
html, body {
margin: 0;
height: 100%;
}
.container {
width: 80vw;
border: 2px solid #4a90e2;
aspect-ratio: 16 / 9;
background-color: #d0e6ff;
margin: 20px auto;
}
Output
A horizontally centered light blue rectangle with a blue border that always keeps a 16:9 shape, resizing with the browser width.
Common Pitfalls
Common mistakes include:
- Using
aspect-ratiowithout setting width or height, which may cause no visible effect if the element has no size. - Expecting
aspect-ratioto work on inline elements (it works on block or replaced elements). - Not accounting for padding or borders that can affect the final size.
css
/* Wrong: no size set, so aspect-ratio has no effect */ .box { aspect-ratio: 4 / 3; background: lightcoral; } /* Right: set width, height adjusts automatically */ .box { width: 200px; aspect-ratio: 4 / 3; background: lightcoral; }
Output
The first box is invisible or has zero height; the second box is visible with width 200px and height 150px (4:3 ratio).
Quick Reference
| Property | Description | Example |
|---|---|---|
| aspect-ratio | Sets width-to-height ratio | aspect-ratio: 16 / 9; |
| width | Sets element width | width: 300px; |
| height | Sets element height (usually auto with aspect-ratio) | height: auto; |
| block or replaced elements | Elements where aspect-ratio works well | div, img, video |
Key Takeaways
Use
aspect-ratio to keep element proportions consistent regardless of size.Set either width or height so the other dimension adjusts automatically.
Works best on block or replaced elements like
div, img, or video.Avoid using
aspect-ratio on inline elements or without size constraints.Remember padding and borders can affect the final visible size.