How can I fill a div with an image while keeping it proportional?
Apply CSS background-size: cover; to your div in order to scale your image, making sure it fills the area without stretching. Implement as followed:
This constrains the image to preserve its aspect ratio while filling the div, and it auto-adjusts in accordance with the div size.
The nitty-grity explained, options included
In some specific scenarios, you might need to inject the image using an <img> element rather than as a background. By pairing object-fit: cover; with setting both width and height to 100%, the image completely fills its container while maintaining its proportion:
Preventing the overflow party
Whenever utilizing object-fit, parts of the image might end up outside of your container. HANDLE the situation by setting your container div overflow property to hidden;, avoiding pesky scrollbars and maintaining the dope layout.
Responsively fitting images and viewport units
Aiming for a responsive design? Bet. Use viewport units (vw/vh) for the dimensions of your container. The viewport units with object-fit: cover combo guarantees your image scales in harmony across all devices :
Mastering it all with the background property shorthand
Lucky for us, CSS includes a shorthand background property that clubs all background- specific properties. This comes in handy when trying to control the size of a transparent gif or image using background properties:
Constraint the image with max/min properties
Sometimes you just want to control the image size while still allowing some flexibility. Apply max-width, max-height, min-width, and min-height to constrain those liberal dimensions, especially when dealing with fluid layouts :
Cross-browser compatibility matters
The object-fit as helpful as it is, unfortunately might not be supported by all browsers, especially the grandpas in the browser-world. No worries though - consider using polyfills, or alternative methods like resorting back to our good friend background-size for background images.
Viable Alternatives to object-fit
If object-fit is acting pricey and not viable, fear not. We have another workaround. Just pop in a transparent gif as a placeholder in the img tag, and set the real image as a background with background-size: cover;:
This strategy leverages the layout properties of the img tag whilst controlling the background image's size. It's basically a two-for-one deal!
Was this article helpful?