Course contentsShow
← Web Development
Lesson 1265 of 2,98222. Responsive Images and MediaFree lesson

Object-fit for Image Cropping Control

Use object-fit (cover, contain, fill) to control how images fill their containers while maintaining aspect ratio.

Object-fit for Image Cropping Control

You'll learn how to control how images fill their containers while maintaining or ignoring their aspect ratio using CSS object-fit.

When you set a fixed width and height on an image container, the image inside might stretch, squash, or distort awkwardly. The object-fit property gives you precise control over how images (and videos) behave inside their defined dimensions.

The Core Idea

Think of object-fit like choosing how to frame a photo in a picture frame. Do you want the entire photo visible even if it leaves gaps? Do you want to fill the frame completely, even if it means cropping parts of the image? The object-fit property lets you decide.

The Five Values

object-fit: cover – Fills the entire container while maintaining aspect ratio. The image may be cropped, but no empty space appears. Like a full-bleed magazine photo.

object-fit: contain – Fits the entire image inside the container while maintaining aspect ratio. May leave empty space (letterboxing). Like viewing a widescreen movie on an old TV.

object-fit: fill – Stretches or squashes the image to fill the container completely, ignoring aspect ratio. Often creates distortion.

object-fit: none – Displays the image at its natural size, potentially overflowing or leaving space.

object-fit: scale-down – Uses whichever is smaller: none or contain.

Common Pattern

img {
  width: 300px;
  height: 200px;
  object-fit: cover; /* Fills box, crops if needed */
}

This ensures all images in a gallery display at consistent dimensions without distortion, even if source images have different aspect ratios.

Key Takeaway: Use object-fit: cover to fill containers while cropping excess, contain to show the full image with potential gaps, and fill when distortion is acceptable—giving you flexible control over responsive image presentation.