Home > Web Front-end > CSS Tutorial > How to Preserve Image Aspect Ratio Inside a Div Using CSS?

How to Preserve Image Aspect Ratio Inside a Div Using CSS?

DDD
Release: 2024-11-12 07:18:01
Original
215 people have browsed it

How to Preserve Image Aspect Ratio Inside a Div Using CSS?

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

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>
Copy after login
.image-container {
  width: 48px;
  height: 48px;
}

.image-container img {
  max-height: 100%;
  max-width: 100%;
}
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template