Course contentsShow
← Web Development
Lesson 2710 of 2,98248. File Uploads and HandlingFree lesson

Preview Dimensions and Aspect Ratios

Use CSS object-fit and aspect-ratio to maintain image proportions while fitting previews into consistent containers.

Preview Dimensions and Aspect Ratios

What you'll learn: How to maintain consistent, proportional image previews using modern CSS properties like object-fit and aspect-ratio.

When displaying image previews after users select files, you face a common challenge: images come in all shapes and sizes—portraits, landscapes, squares—but your UI needs consistent, predictable containers. Without careful styling, images either distort or break your layout.

The Core Problem

You've already learned to display image previews in the DOM. Now you need them to look professional. Imagine a photo gallery where one preview is tall and narrow, another short and wide—chaos! You want uniform containers that respect each image's original proportions.

The CSS Solution

Modern CSS gives you two powerful tools:

object-fit controls how an image fills its container. Think of it like cropping modes in photo apps:

  • cover: fills the entire container, cropping excess (like a profile picture)
  • contain: fits the whole image inside, adding letterboxing if needed
  • fill: stretches to fill (usually distorts—avoid this)

aspect-ratio enforces a width-to-height ratio on the container itself, keeping dimensions predictable regardless of content.

Example Pattern

.image-preview {
  width: 200px;
  aspect-ratio: 1 / 1; /* Square container */
  overflow: hidden;
  border: 1px solid #ddd;
}

.image-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover; /* Fills square, crops if needed */
}

This creates uniform square thumbnails. Change aspect-ratio: 16 / 9 for widescreen rectangles, or use object-fit: contain to show the entire image with padding instead of cropping.

Key Takeaway: Use aspect-ratio on containers to enforce consistent dimensions, and object-fit on images to control how they fill those containers while maintaining their natural proportions—no JavaScript math required.