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

Susan Sarandon
Release: 2024-11-10 12:11:02
Original
399 people have browsed it

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

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!

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