How do you stretch an image to fill a <div> while keeping the image's aspect-ratio?
To make an image snugly occupy a div while preserving its aspect-ratio, use CSS's object-fit: cover;. Ensure the image fills the div by using width: 100%; height: 100%;. Here's an example:
As a best practice, make sure your div has set dimensions.
A closer look at object-fit
The object-fit property offers a treasure trove of options for tailoring image fit:
fill: Disregards the aspect ratio and stretches the image to fit thediv.contain: Keeps the aspect ratio while fitting the entire image within thediv.cover: Ensures the image covers thediv, while maintaining its aspect ratio.none: The image keeps its original dimensions, doesn't resize to fit thediv.scale-down: Picks the 'smallest version' betweennoneandcontain.
When object-fit doesn't fit
For vintage browsers that don't support object-fit, a fallback method is to set the image as a div background:
Remember to set the URL of your image in the background-image property, and the div dimensions for the image to scale perfectly.
Sizing matters
If the size of your div is being fickle, set your div dimensions using responsive units, such as percentages:
This ensures the div scales with the viewport or its parent container while maintaining your image intact.
jQuery strikes back
When dealing with unpredictable div sizes or image aspect ratios, runtime flexibility can save you. Here's where jQuery can chip in:
Then in CSS, assign Oscar-worthy styles to .wide and .tall classes.
Keeping it inside the lines
If your use-case calls for the image to proudly sit within a div without violating boundaries, use max-width: 100% and max-height: 100% for your image:
This ensures the image will not exceed the div space and adapts to the div dimensions.
Going beyond object-fit
If object-fit is not cutting it for you, CSS transform is another viable ally:
You can adjust the scale value for a sweeter fit, but remember, with overflowing power, comes overflowing responsibility.
Conclude that code
Coding is an art, and you just finished a piece. If this information has been helpful and you've been able to compose your masterpiece — do us all a favor and click that upvote. Happy coding!👩💻
Was this article helpful?