When displaying an image within a restricted space, it's often desirable to fit it without compromising its aspect ratio. HTML and CSS provide an elegant solution to achieve this.
The key to maintaining the image's aspect ratio is to utilize the max-height and max-width CSS properties. Here's how to implement it:
Apply max-height and max-width to the image:
By doing so, the image will shrink or expand within the div's boundaries while preserving its aspect ratio.
Consider the following HTML and CSS code:
<div>
In this example, the image "my-image.jpg" will dynamically adjust its size to fit within the 48x48 div, maintaining its original proportions.
The above is the detailed content of How to Preserve Aspect Ratio While Fitting an Image Within a Div?. For more information, please follow other related articles on the PHP Chinese website!