Is there an equivalent to background-size: cover and contain for image elements?
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:
Implementing it in your <img> tag:
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:
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:
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.
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.
Was this article helpful?