Filling a Div with an Image Proportionally
In this thread, a user seeks to fill a div with an image while maintaining the aspect ratio, regardless of the image orientation. The div has overflow hidden, allowing for potential image cropping.
To address this issue, it's recommended to remove the width and height attributes from the image to preserve its natural aspect ratio. Flexbox can then be employed to center the image within the div.
Here's a CSS snippet to achieve this:
.fill { display: flex; justify-content: center; align-items: center; overflow: hidden } .fill img { flex-shrink: 0; min-width: 100%; min-height: 100% }
And a corresponding HTML example:
<div class="fill"> <img src="https://picsum.photos/id/237/320/240" alt="" /> </div>
This solution utilizes flexbox to center the image and ensure that it fills the div, preserving its proportions.
The above is the detailed content of How Can I Proportionally Fill a Div with an Image While Maintaining Aspect Ratio?. For more information, please follow other related articles on the PHP Chinese website!