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!