Home > Web Front-end > CSS Tutorial > How Can I Make an Image Fill a Div While Maintaining its Aspect Ratio Using Flexbox?

How Can I Make an Image Fill a Div While Maintaining its Aspect Ratio Using Flexbox?

Mary-Kate Olsen
Release: 2024-11-24 06:28:14
Original
366 people have browsed it

How Can I Make an Image Fill a Div While Maintaining its Aspect Ratio Using Flexbox?

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%;
}
Copy after login

Explanation:

  • Set the container div to display: flex and center its content.
  • Specify flex-shrink: 0 on the image to prevent it from shrinking.
  • Set min-width: 100% and min-height: 100% to ensure the image fills the div.

Example:

<div class="container">
  <img src="some-image.jpg" alt="Could be portrait or landscape">
</div>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template