object-fit & aspect-ratio

Master responsive media by controlling image scaling without distortion and locking container proportions.

CSS6 min readConcept 28 of 43

What they are

aspect-ratio allows you to lock an element's proportions. If you set aspect-ratio: 16 / 9, the browser will automatically calculate the height based on the width to maintain that exact rectangle.

object-fit dictates how the content of a replaced element (like an <img> or <video>) should resize to fit its container.

Why it matters

When building responsive grids (like a gallery of product photos), you usually want all image boxes to be exactly the same size. But user-uploaded photos come in all shapes and sizes.

If you force an image to be width: 100% and height: 100%, it will squish and stretch to fit the box, looking terrible.

object-fit: cover solves this by telling the image to fill the box entirely while maintaining its intrinsic proportions, cropping any overflow.

How to use them

1. **Lock the box**: Apply aspect-ratio: 1 / 1 (a perfect square) to the image container.

2. **Fill the box**: Make the image fill the container using width: 100%; height: 100%.

3. **Fix the distortion**: Apply object-fit: cover to the image to crop it perfectly, or object-fit: contain to letterbox it.

Try it

Toggle the different object-fit values to see how the browser resolves the conflict between the image's original dimensions and its fixed container size.

Image Scaling

object-fit

How should the wide 2:1 image fit into the 1:1 square box?

/* 1. Lock the container's proportions */
.container {
aspect-ratio: 1 / 1;
width: 240px;
overflow: hidden;
}
// 2. Control how the image fits inside
img {
width: 100%;
height: 100%;
object-fit: cover;
}
Aspect-ratio 1:1240px
Demo 2:1 rectangle

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1If you have a square container but a tall, rectangular image, what will `object-fit: cover` do?
  2. 2If an element has `width: 400px` and `aspect-ratio: 4 / 1`, what will its height be?
  3. 3How does `aspect-ratio` help improve a website's Core Web Vitals score?

Remember this

  • aspect-ratio: w / h locks an element's proportions, reserving space before images load to prevent layout shifts.
  • Forcing an image's width and height causes terrible distortion.
  • object-fit: cover fixes distortion by filling the box and cropping the overflow.
  • object-fit: contain fixes distortion by shrinking the image to fit entirely, leaving empty letterbox space.

Done with this concept?

Mark it complete to track your progress. No login needed.