1. aspect-ratio Basics

Set dimensions with ratios instead of fixed heights so media blocks stay stable across screen sizes.

16:9 frame

Good default for videos and hero banners.

1:1 frame

Useful for product grids and social cards.

4:3 frame

A balanced ratio for article previews.

.thumb-wide { aspect-ratio: 16 / 9; }
.thumb-square { aspect-ratio: 1 / 1; }
.thumb-portrait { aspect-ratio: 3 / 4; }

2. object-fit Modes

object-fit controls how media fills its box when source and container ratios differ.

cover
demo cover

Fills the frame and may crop content. Great for cards.

contain
demo contain

Shows full media with potential empty space.

fill
demo fill

Stretches media to match box size and can distort.

img.card-media {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

3. object-position for Crop Focus

When using cover, use object-position to keep faces, products, or key details in frame.

Top focus
demo top position

object-position: top center;

Center focus
demo center position

object-position: center;

Bottom-right focus
demo bottom position

object-position: bottom right;

.avatar-hero {
  object-fit: cover;
  object-position: top center;
}

4. Prevent Layout Shift with Placeholders

Reserve media height before files load so content does not jump. This improves perceived quality and Core Web Vitals.

Aspect-ratio placeholder

Use ratio boxes as loading placeholders to keep layout stable.

.image-shell {
  aspect-ratio: 16 / 9;
  background: #e2e8f0;
}
.image-shell > img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

Create predictable galleries with shared ratio rules. The layout stays tidy even when source files have different dimensions.

Square gallery grid

Shared aspect-ratio: 1 / 1 keeps rows aligned.

.gallery {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 0.75rem;
}
.gallery-item {
  aspect-ratio: 1 / 1;
  overflow: hidden;
}
.gallery-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}