← Lessons

quiz vs the machine

Gold1340

Frontend

The Aspect Ratio Property

Reserve proportional space and stop layout shift by declaring width to height ratios directly.

4 min read · core · beat Gold to climb

Declaring a ratio

The aspect ratio property tells a box to keep a width to height proportion. You write it as two numbers separated by a slash, such as sixteen by nine. When one dimension is known, the browser computes the other from the ratio.

  • A value of one by one makes a perfect square.
  • The ratio applies until an explicit height overrides it.
  • It replaces the old padding percentage hack for responsive boxes.

Preventing layout shift

A frequent cause of layout shift is media that loads without reserved space. Giving a replaced element like an image or video an aspect ratio lets the browser hold the right space before the file arrives.

  • Set width to a flexible value and let the ratio derive height.
  • The box reserves space so surrounding content does not jump.
  • If both width and height are set, the explicit sizes win and the ratio is ignored.

The property also works on non replaced elements such as cards and embeds that should keep a shape.

Key idea

Aspect ratio fixes a box proportion so the browser derives the missing dimension and reserves space ahead of media, eliminating a major source of layout shift.

Check yourself

Answer to earn rating on the learn ladder.

1. What happens when both width and height are explicitly set on a box with an aspect ratio?

2. Why does setting aspect ratio on an image help performance metrics?