Good default for videos and hero banners.
1. aspect-ratio Basics
Set dimensions with ratios instead of fixed heights so media blocks stay stable across screen sizes.
Useful for product grids and social cards.
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.
Fills the frame and may crop content. Great for cards.
Shows full media with potential empty space.
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.
object-position: top center;
object-position: center;
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.
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;
}5. Gallery and Card Pattern
Create predictable galleries with shared ratio rules. The layout stays tidy even when source files have different dimensions.
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;
}