Skip to content
Tutorials Center
My learning

Topics

Lesson 51 of 139 ยท Backgrounds and Effects

Sizing Images: object-fit and aspect-ratio

Fit images and videos into fixed boxes without distortion using object-fit and object-position, and keep any element in proportion with aspect-ratio.

Real content is messy. A product grid receives photos in every shape: wide shots, tall shots, squares. If you force them all to the same width and height, the browser stretches them and faces turn into funhouse mirrors. If you leave them alone, your neat grid becomes a jagged mess.

CSS solves this with two tools. object-fit and object-position control how an image or video fills the box you give it, much like background-size and background-position do for backgrounds. aspect-ratio lets you define the shape of that box in the first place, so a card can always be 16:9 or a thumbnail always square, whatever its width.

The problem: replaced elements stretch

An <img> is a replaced element: its content comes from outside the page, and it has its own natural size and proportions. If you set only width, the browser works out the height from the natural proportions, and everything looks right. Trouble starts when you set both dimensions to a shape that does not match the image:

CSS
.thumb {
  width: 200px;
  height: 200px;   /* the image is 320 ร— 200, not square */
}

By default the image is squeezed to fit exactly, because the default value of object-fit is fill. The fix is not to avoid fixed boxes, which are often exactly what a design needs. The fix is to tell the browser how to fit the picture inside them.

object-fit

object-fit works on replaced elements like <img>, <video>, <canvas> and <iframe>. Its values match what you already know from background-size:

Value What happens
fill Stretch to fill the box exactly (the default; can distort).
cover Scale, keeping proportions, until the box is covered; the overflow is cropped.
contain Scale, keeping proportions, until the whole image fits; empty space may remain.
none Keep the natural size; crop if it is bigger than the box.
scale-down Use none or contain, whichever gives the smaller image.

The element's box stays the size you set. Only the picture inside it changes. Empty space left by contain shows the element's own background, so you can give it a color.

The five object-fit values

Look at the sun in each box. With fill it becomes an oval, with cover it stays round but the sides are cut away, and with contain the whole landscape fits with gray bands above and below. Because the image is larger than the box, scale-down behaves like contain here. Change the image size to 400px by 300px and it switches to behave like none.

Cropping is not the same as hiding. With cover, the whole image is still downloaded and only part of it is shown. If you need different crops for phones and desktops, serve different files with <picture>, as shown in Responsive Images.

object-position

When cover or none crops an image, which part survives? By default the image is centered, so the edges are cut away evenly. object-position moves it, using the same syntax as background-position:

CSS
.avatar {
  object-fit: cover;
  object-position: center top;   /* keep the top: heads, not feet */
}
.banner {
  object-fit: cover;
  object-position: 30% 70%;      /* a specific focal point */
}

This tall lighthouse picture shows why it matters. In a wide, short box, the default crop keeps the middle of the tower and cuts off the lamp:

Choosing the crop with object-position

object-position also works with contain: it decides where the empty bands go. object-position: left with contain pins a logo to the left edge of its box.

aspect-ratio

object-fit needs a box with a known shape. Fixed pixel heights work, but they fight with responsive layouts: a 200px-tall card looks fine at one width and wrong at another. What you usually want is a box whose proportions are fixed while its width stays fluid. That is aspect-ratio:

CSS
.video-frame {
  width: 100%;
  aspect-ratio: 16 / 9;
}
.square { aspect-ratio: 1; }      /* same as 1 / 1 */

The value is width divided by height. When one dimension is automatic (usually the height), the browser calculates it from the other. If you set both width and height explicitly, aspect-ratio is ignored, because there is nothing left to calculate.

aspect-ratio works on any element, not just images. It is perfect for video embeds, placeholder boxes, map containers, cards and avatars. It has been supported in all major browsers since 2021.

A fluid gallery with aspect-ratio and object-fit

Three images with three different natural shapes (landscape, portrait and 16:9) all become tidy squares. Resize the preview and the tiles grow and shrink, staying square. The grid code is covered later in Grid Tracks: fr, repeat() and minmax(); the important part for now is the two lines in the middle.

Ratios with auto

You can write aspect-ratio: auto 4 / 3. For replaced elements like images, this means "use the image's natural ratio once it is known, and use 4 / 3 until then". That is a useful placeholder while an image is loading.

In fact browsers already do something like this for you. When an <img> has width and height attributes, the browser's built-in stylesheet turns them into an auto aspect ratio, so the space is reserved before the image arrives. Combine that with max-width: 100%; height: auto; in your CSS and images scale down without stretching and without the page jumping when they load:

HTML
<img src="/samples/sunset.svg" width="320" height="200" alt="Sunset">
CSS
img {
  max-width: 100%;
  height: auto;
}

Always give images width and height attributes. They reserve space before the file arrives, so text below the image does not jump down. That jump is called layout shift, and it hurts both users and your search ranking.

Content can override the ratio

aspect-ratio sets a preferred size. If a box with aspect-ratio: 1 contains more text than fits, the box grows taller rather than letting the text overflow, because by default its minimum height is based on its content. If you really want the ratio to win, add min-height: 0 or overflow: auto, and the content scrolls or overflows instead.

aspect-ratio on ordinary boxes

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the default value of object-fit?

    fill stretches the image to the box, which is why images with a mismatched width and height look distorted until you change it.
  2. 2. You want every product photo to fill its square tile completely without distortion. Which declaration fits?

    cover keeps the proportions and crops whatever does not fit, so the tile is always full.
  3. 3. A cropped portrait keeps cutting off people's heads. What helps?

    object-position chooses which part of the image stays visible; aligning to the top keeps heads in view.
  4. 4. An element has width: 100% and aspect-ratio: 16 / 9. What happens when it gets wider?

    With an automatic height, the browser calculates the height from the width and the ratio.
  5. 5. Why should an <img> have width and height attributes even if CSS resizes it?

    The browser turns the attributes into an aspect ratio, so it can lay out the page correctly before the file arrives.

Summary

  • Setting both width and height on an image stretches it, because object-fit defaults to fill.
  • object-fit: cover fills the box and crops; contain shows everything and may leave bands; none and scale-down avoid enlarging.
  • object-position picks the visible part of a cropped image, using background-position syntax.
  • aspect-ratio gives any element fixed proportions while its width stays fluid.
  • Images with width and height attributes plus max-width: 100%; height: auto scale safely without layout shift.
  • Content can make an aspect-ratio box taller unless you allow overflow.

Next: Styling Images.