Home  >  Article  >  Web Front-end  >  How to Fit an Image Within a Div While Preserving Aspect Ratio?

How to Fit an Image Within a Div While Preserving Aspect Ratio?

Susan Sarandon
Susan SarandonOriginal
2024-11-10 12:11:02405browse

How to Fit an Image Within a Div While Preserving Aspect Ratio?

Preserving Aspect Ratio While Fitting an Image within a Div

When working with web designs, a common task is to fit an image within a div while maintaining its aspect ratio. This ensures that the image does not get distorted and retains its intended proportions. To achieve this in HTML and CSS, we can utilize the following code:

.my-div {
   width: 48px;
   height: 48px;
   overflow: hidden;
}

.my-img {
   max-height: 100%;
   max-width: 100%;
}

Inside the CSS, we define a class for the div (my-div) with a fixed width and height. The overflow property is set to hidden to conceal any image content that goes beyond the div's boundaries.

Within the div, an image class (my-img) is defined. The trick here lies in setting both max-height and max-width to 100%. This allows the image to fully occupy the space within the div while adhering to its own aspect ratio. Without these rules, the image would stretch or squash to fit the div's dimensions, resulting in distortion.

By implementing this code, you can successfully fit an image within a div while preserving its aspect ratio. This technique is particularly useful for ensuring responsive image displays across various screen sizes and devices.

The above is the detailed content of How to Fit an Image Within a Div While Preserving 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