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

How Can I Fill a Div with an Image While Preserving Its Aspect Ratio?

DDD
Release: 2024-11-21 09:25:11
Original
362 people have browsed it

How Can I Fill a Div with an Image While Preserving Its Aspect Ratio?

Filling a Div with an Image While Maintaining Proportions

In web development, you may encounter the need to display an image within a div element while ensuring that the image's aspect ratio remains intact. This can be a tricky problem, but a solution lies in combining CSS flexbox and careful image sizing.

Consider this scenario: you have a div element with a fixed size and an image within it. You want the image to always fill the div, regardless of whether it's a landscape or portrait orientation. This requirement can be met even if the image gets cut off because the div has overflow: hidden set.

To achieve this effect, follow these steps:

  • Remove the width and height attributes from the image tag to maintain its aspect ratio.
  • Set the div element to use flexbox with display: flex.
  • Use justify-content: center and align-items: center on the div to center the image within it.
  • Add overflow: hidden to the div to crop any excess image that extends beyond its size.
  • Style the image within the div as follows:
.fill img {
    flex-shrink: 0;
    min-width: 100%;
    min-height: 100%
}
Copy after login
  • The flex-shrink: 0 ensures that the image doesn't shrink if the div becomes smaller.
  • The min-width: 100% and min-height: 100% ensure that the image is always at least as large as the div.

Using this technique, you can fill a div with an image while maintaining its proportions, regardless of its orientation.

The above is the detailed content of How Can I Fill a Div with an Image While Preserving Its Aspect Ratio?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template