Home >Web Front-end >CSS Tutorial >How Can I Proportionally Fill a Div with an Image While Maintaining Aspect Ratio?

How Can I Proportionally Fill a Div with an Image While Maintaining Aspect Ratio?

Linda Hamilton
Linda HamiltonOriginal
2024-11-19 02:55:02348browse

How Can I Proportionally Fill a Div with an Image While Maintaining Aspect Ratio?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn