Course contentsShow
← Web Development
Lesson 2033 of 2,98237. Image and Asset OptimizationFree lesson

Aspect Ratio Boxes

Reserve correct space using padding-top trick or aspect-ratio property to prevent layout shift during image loading.

Aspect Ratio Boxes

What you'll learn: How to reserve the correct amount of space for images before they load, preventing annoying content jumps on your page.

The Layout Shift Problem

When an image hasn't loaded yet, the browser doesn't know how tall it should be. This causes content below the image to suddenly jump downward once the image finally appears—creating a jarring user experience called Cumulative Layout Shift (CLS).

Think of it like reserving a parking spot: you mark off the exact space needed before the car arrives, so nothing needs to move when it shows up.

The Padding-Top Trick

One classic technique uses CSS padding percentages, which are always calculated based on the element's width:

.aspect-ratio-box {
  position: relative;
  width: 100%;
  padding-top: 56.25%; /* 16:9 ratio (9/16 * 100) */
  background: #f0f0f0; /* placeholder color */
}

.aspect-ratio-box img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

For a 16:9 image, you calculate: (9 ÷ 16) × 100 = 56.25%. The padding creates the height while the image positions absolutely inside.

The Modern Approach: aspect-ratio Property

CSS now offers a simpler solution:

.image-container {
  aspect-ratio: 16 / 9;
  width: 100%;
  background: #f0f0f0;
}

img {
  width: 100%;
  height: auto;
}

This reserves the space with cleaner, more readable code. The browser holds the exact dimensions before the image loads, eliminating layout shift.

Key Takeaway: Use aspect ratio boxes (either padding-top trick or the aspect-ratio property) to reserve image space upfront, preventing content from jumping around during load and improving your Core Web Vitals scores.