Preserving Aspect Ratio of an Image Inside a Div
Often, it's desirable to display an image within a div while maintaining its aspect ratio. This ensures that the image is fully visible without any distortion. To achieve this, you can leverage specific CSS properties.
Solution using CSS:
Inside the div where the image is placed, add the following CSS rules to the image element:
max-height: 100%; max-width: 100%;
These CSS properties instruct the browser to constrain the dimensions of the image within the boundaries of the div. The max-height property limits the vertical size, while max-width restricts the horizontal size. By setting both properties to 100%, the image is scaled down to fit within the div while preserving its original aspect ratio.
Example:
<div class="image-container"> <img src="image.jpg" /> </div>
.image-container { width: 48px; height: 48px; } .image-container img { max-height: 100%; max-width: 100%; }
This example will fit a 48x48 image inside a 48x48 div while maintaining the image's aspect ratio. The image will be resized to display fully within the div without any cropping or distortion.
The above is the detailed content of How to Preserve Image Aspect Ratio Inside a Div Using CSS?. For more information, please follow other related articles on the PHP Chinese website!