How to Use object-fit: cover in CSS for Responsive Images
Use the CSS property
object-fit: cover; on an image or video to make it fill its container completely while keeping its aspect ratio. This causes the content to be cropped if it doesn't match the container's shape, ensuring no empty space is visible.Syntax
The object-fit property controls how the content of a replaced element like an <img> or <video> fits inside its container box.
Using object-fit: cover; means the content will fill the container entirely, cropping parts if needed, while preserving the original aspect ratio.
css
img {
width: 300px;
height: 200px;
object-fit: cover;
}Example
This example shows an image inside a fixed-size box. The image uses object-fit: cover; to fill the box completely, cropping parts if the image's shape doesn't match the box.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>object-fit cover Example</title> <style> .container { width: 300px; height: 200px; border: 2px solid #333; overflow: hidden; } .container img { width: 100%; height: 100%; object-fit: cover; } </style> </head> <body> <div class="container"> <img src="https://images.unsplash.com/photo-1506744038136-46273834b3fb?auto=format&fit=crop&w=600&q=80" alt="Nature"> </div> </body> </html>
Output
A 300px by 200px box with a nature photo filling it completely, cropped on sides or top/bottom to fit without distortion.
Common Pitfalls
One common mistake is not setting both width and height on the image or its container. Without fixed dimensions, object-fit: cover; has no effect.
Another issue is using object-fit on elements that don't support it, like background images. For backgrounds, use background-size: cover; instead.
css
/* Wrong: no fixed size, object-fit won't work */ img { object-fit: cover; } /* Right: fixed size with object-fit */ img { width: 300px; height: 200px; object-fit: cover; }
Quick Reference
- object-fit: cover; fills container, crops overflow, keeps aspect ratio.
- Requires fixed
widthandheighton the element or container. - Works only on replaced elements like
<img>,<video>. - For background images, use
background-size: cover;instead.
Key Takeaways
Use object-fit: cover to make images fill their container while preserving aspect ratio and cropping overflow.
Always set fixed width and height on the image or its container for object-fit to work.
object-fit applies only to replaced elements like images and videos, not background images.
For background images, use background-size: cover instead of object-fit.
object-fit: cover helps create responsive, visually pleasing image layouts without distortion.