🌐 What is object-fit?
object-fit is a CSS property that controls how replaced elements like <img>, <video>, and <picture>should resize inside their containers. It works similarly to background-size, but for actual media elements.
Note
✔ Perfect for responsive images, thumbnails, banners, and galleries
🎯 Why Use object-fit?
- Prevent image distortion (stretching/squashing)
- Maintain correct aspect ratio
- Create cropped thumbnails
- Fill hero banners responsively
- Control video scaling inside player containers
📌 Syntax
object-fit Syntax
object-fit: fill | contain | cover | none | scale-down;🎨 Values Explained
| Value | Behavior |
|---|---|
| fill (default) | Fills the box; image may stretch |
| contain | Fits entire image inside box; may add empty space |
| cover | Fills box completely; image may be cropped |
| none | No resizing; original size is preserved |
| scale-down | Acts like none or contain, whichever is smaller |
🖼️ Example 1 — object-fit: cover
Cover Example
img.hero {
width: 100%;
height: 300px;
object-fit: cover;
}Great for hero banners — fills width & height, cropping edges as needed.
🖼️ Example 2 — object-fit: contain
Contain Example
img.logo {
width: 200px;
height: 200px;
object-fit: contain;
background: #f3f3f3;
}Ensures full image is visible — useful for logos and icons.
🖼️ Example 3 — object-fit: fill
Fill Example
img.stretch {
width: 300px;
height: 200px;
object-fit: fill;
}The image fully fills the box but may distort. Avoid for non-decorative images.
🖼️ Example 4 — object-fit + Videos
Video Example
video {
width: 100%;
height: 400px;
object-fit: cover;
}Video stays center-cropped like modern media players.
📐 Using object-position
Use object-position to control the cropping focus.
object-position Example
img {
object-fit: cover;
object-position: top center;
}Crops from sides but keeps the top area visible — great for portraits.
📱 Responsive Use Case — Image Grid
Responsive Gallery
.gallery img {
width: 100%;
height: 150px;
object-fit: cover;
}Ensures uniform grid thumbnails regardless of image dimensions.
🧠 How object-fit Behaves
- cover = crop but fill the box
- contain = show full image, no cropping
- fill = stretch if needed
- none = no scaling
- scale-down = smallest possible version
Note
⚠️ Common Mistakes
- ❌ Expecting object-fit to work on background images (use background-size instead)
- ❌ Forgetting to set width & height of container
- ❌ Using fill on photos → leads to distortion
- ❌ Not using object-position when cropping matters
🔥 Summary
object-fit is one of the most powerful CSS tools for controlling how images and videos behave inside fixed-size containers. Whether you're designing hero banners, galleries, logos, or media components, object-fit ensures perfect scaling and cropping.
Learn more →MDN Docs 📘