CSS object-fit and object-position
Control how images and videos fill their containers using object-fit (cover, contain, fill) and object-position for alignment.
Overview
Key Points
- •object-fit: cover fills the container and crops exactly like background-size: cover
- •object-fit: contain shows the entire image with possible letterboxing
- •object-fit: fill (default) stretches the image almost always unwanted
- •object-position: top keeps the top of the image visible when cover crops
- •You must set an explicit width and height on the img/video for object-fit to work
- •object-fit replaces the old hack of using background-image for aspect-ratio-controlled images
- •Combine with aspect-ratio for completely responsive media containers
Examples
Card images with consistent height
.card-img {
width: 100%;
height: 200px;
object-fit: cover;
object-position: center;
border-radius: 12px 12px 0 0;
display: block;
}
/* Show top of portrait photos e.g., person's face */
.avatar-img {
width: 60px;
height: 60px;
object-fit: cover;
object-position: top;
border-radius: 50%;
}object-position: top ensures face is visible in portrait photos when the container is square.
Video background that fills without distortion
.video-hero {
position: relative;
height: 100dvh;
overflow: hidden;
}
.video-hero video {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
object-fit: cover; /* fills without stretching */
}Logo wall with contain to preserve branding
.logo-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
gap: 24px;
align-items: center;
}
.logo-img {
width: 100%;
height: 60px;
object-fit: contain; /* shows full logo, no cropping */
object-position: center;
filter: grayscale(1) opacity(0.5);
transition: filter 0.2s ease;
}
.logo-img:hover {
filter: grayscale(0) opacity(1);
}Logos should use contain, not cover you want the full mark visible, not cropped.
Common Mistakes
- Forgetting to set an explicit height on the img element without height, object-fit has nothing to fill
- Using object-fit: cover on a logo and cropping out the brand name use contain for logos
- Using object-fit without display: block on the img inline images have extra space from the baseline; always add display: block
Note
For a responsive image container that maintains aspect ratio, combine aspect-ratio with object-fit: cover it's cleaner than the old padding-top padding hack. Example: img { aspect-ratio: 16/9; width: 100%; object-fit: cover; }
Exercises
Write CSS to style the HTML scaffold. The preview updates live — when it looks right, mark as done.
Completed: 0 / 5 exercises
Knowledge Check
Question 1 of 4