What is object-fit?
object-fit is a CSS property that defines how an element (like <img> or <video>) should resize to fit its container. It solves the common problem of distorted images by controlling aspect ratio behavior, similar to background-size but for replaced elements.
object-fit Values
| Value | Behavior | Use Case | Example |
|---|---|---|---|
| fill | Stretches to fill container | Not recommended (distorts) | width: 100%; height: 100%; |
| contain | Fits entirely inside container | Product images, logos | Preserves ratio, may have empty space |
| cover | Fills container, crops if needed | Hero images, thumbnails | Preserves ratio, fills completely |
| none | Original size, may overflow | Pixel art, exact sizing | No resizing |
| scale-down | Smaller of none or contain | Fallback option | Shows smallest version |
Basic Syntax
Visual Comparison
object-position: Positioning the Content
Practical Examples
Advanced object-position Techniques
object-fit for Videos
Browser Support & Fallbacks
Common Use Cases
Aspect Ratio Integration
Performance Considerations
- Use appropriate image sizes – object-fit doesn't reduce file size, serve properly sized images
- Combine with srcset – Responsive images + object-fit = perfect combination
- Avoid object-fit on animated GIFs – Can cause performance issues
- Use will-change sparingly – Only for frequently animated images
- Hardware acceleration – object-fit is GPU accelerated in modern browsers
- Lazy loading – Combine with loading="lazy" for off-screen images
Best Practices
- Use cover for hero images – Ensures full bleed with no empty space
- Use contain for product photos – Shows entire product without cropping
- Set explicit width/height – Prevents layout shift (CLS)
- Add background color – For contain or scale-down, shows during loading
- Combine with border-radius – Works perfectly for rounded corners
- Test different aspect ratios – Ensure important content isn't cropped
- Use object-position strategically – Focus on the most important part
- Provide fallbacks – For older browsers (IE doesn't support object-fit)
Common Mistakes
- Forgetting to set height – object-fit needs explicit dimensions
- Using fill by default – Distorts images, use cover or contain instead
- Not setting object-position – Important parts may be cropped
- Assuming all images have same ratio – Test with portrait and landscape
- Over-optimizing quality – object-fit doesn't affect image quality, just display
- Not providing alt text – Accessibility always matters
Conclusion
object-fit and object-position are essential tools for modern responsive design. They give you precise control over how images and videos behave within their containers, solving common layout issues with minimal CSS. Use cover for full-bleed images, contain for product displays, and object-position to focus on important content. With excellent browser support (except IE), these properties should be part of every frontend developer's toolkit.