Aspect-ratio
Learn aspect ratio with aspect-ratio.
What is aspect-ratio?
Sometimes you want a box to keep a fixed ratio between width and height as the width changes. The aspect-ratio property does exactly that: it holds the width/height ratio steady.
For example, aspect-ratio: 16 / 9 keeps the height tied to the width. A 400-pixel wide box becomes 225 pixels tall. This is ideal for video placeholders and image frames.
Intrinsic ratio
Giving a box an aspect-ratio grants it an intrinsic ratio. As the width changes, the ratio holds; the height is computed automatically.
If the box holds an image and width: 100% is set, the ratio shapes the image too. Fixed-ratio placeholders, fluid images, and video frames now follow this approach as standard practice.
Leave height auto
Sometimes a box has both an aspect-ratio and a fixed height. In that case the browser prefers the explicit height; the ratio only kicks in when the width changes.
If you want a flexible ratio, just write height: auto. This lets the ratio do its job. A fixed height locks the box; the ratio then only applies when the width is set first.
Exercise Give the video placeholder a ratio
Give the .video selector aspect-ratio: 16 / 9 and height: auto. Also add background-color: black. The ratio will hold as the width changes.
Show example solution
/* give the video placeholder a ratio */
.video {
aspect-ratio: 16 / 9;
height: auto;
background-color: black;
}
Test yourself
-
Which gives a 4-unit wide, 3-unit tall ratio?
- aspect-ratio: 3 / 4
- aspect-ratio: 4 / 3
- aspect-ratio: 4-3
- aspect-ratio: ratio(4,3)
Show answer
aspect-ratio: 4 / 3 — Correct. 4 / 3 gives a four-unit wide, three-unit tall ratio.
-
Write the 16:9 ratio
.video { aspect-ratio: ____; }Show answer
.video { aspect-ratio: 16 / 9; }