Proportional Image Filling in a Div
Your goal is to fill a div with an image while preserving the image's aspect ratio. Unlike a previous thread, you want the image to always fill the div, regardless of orientation.
Solution: Flexbox
To achieve this, we can leverage CSS flexbox:
.container { display: flex; justify-content: center; align-items: center; overflow: hidden; } .container img { flex-shrink: 0; min-width: 100%; min-height: 100%; }
Explanation:
Example:
<div class="container"> <img src="some-image.jpg" alt="Could be portrait or landscape"> </div>
The result is an image that fills the div while retaining its aspect ratio. Whether it's portrait or landscape, the image will occupy the entire space.
The above is the detailed content of How Can I Make an Image Fill a Div While Maintaining its Aspect Ratio Using Flexbox?. For more information, please follow other related articles on the PHP Chinese website!