Explain Codes LogoExplain Codes Logo

Is there an equivalent to background-size: cover and contain for image elements?

css
responsive-design
object-fit
css-tricks
Anton ShumikhinbyAnton Shumikhin·Feb 25, 2025
TLDR

The CSS object-fit property will act as your magic wand, replicating background-size: cover and contain for <img> elements. Apply object-fit: cover; to fill the image box while keeping the aspect ratio, or object-fit: contain; to display the entire image within the given box. Here is the basic syntax:

// Leak-proof coffee cup for your elements img { object-fit: cover; /* This says: "Cover is the new black" */ }

Implementing it in your <img> tag:

<!-- Notice, folks: image covering in style --> <img src="path-to-image.jpg" style="object-fit: cover;" alt="Pixar couldn't do it better">

This ensures your image stretches or contracts as needed, giving you the background effect for foreground images.

Clever tricks with images

Working with different browsers: an object-fit affair

Before you slide object-fit into your CSS, make sure it plays nice with your userbase's browsers. Almost every modern browser shakes hands with object-fit, but we do have the outliers. For those, we can go with a div container having background-image and background-size:

.div-container { background: url('path-to-image.jpg') no-repeat center center; background-size: cover; /* Old school, for our IE folks */ }

Harnessing fullscreen effect with object-fit

For an immersive fullscreen effect, object-fit: cover does the job remarkably well, morphing the image to viewport size without any distortion. Combined with viewport units (vh and vw) for a dynamic and responsive design:

/* Call it magic, call it CSS */ .fullscreen-img { width: 100vw; height: 100vh; object-fit: cover; }

Dipping toes into legacy browser compatibility

For those working with legacy browsers like IE8, here's an absolute positioning, overflow: hidden, and generous negative margings cooked together resulting in a centered image replicating background-size: cover.

Dynamic responsiveness: JavaScript to the rescue

For images of varying sizes and orientations, JavaScript can dynamically assign styles ensuring your image fits like a glove regardless of the device screen or resolution. Now, that's what we call a smart fit.

img { transform: scale(1.1); /* An apple a day keeps the scroll away */ }

The trusty JSFiddle resource at http://jsfiddle.net/BuschFunker/sjt71j99/ explains it all.

Photo-fit flexibility based on specific needs

Need images to fit, yet stay true to their natural size? transform: scale() combined with max-width/max-height is your tailor, custom sewing each image for a great fit without compromising the destiny of its dimensions.