Home > Web Front-end > CSS Tutorial > How to Fit an Image Snugly Within a Div While Preserving Aspect Ratio?

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

Linda Hamilton
Release: 2024-11-19 12:25:03
Original
1012 people have browsed it

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

Maintaining Aspect Ratio of Image within a Div

Question:

How can one fit an image snugly within a div element while preserving its aspect ratio, ensuring that no portion of the image is cropped or distorted?

Answer:

To achieve this using CSS, utilize the following properties:

img {
  max-height: 100%;
  max-width: 100%;
}
Copy after login
  1. max-height: 100%;: Sets the maximum height of the image to 100% of its container div. This ensures that the image will not overflow the div's height.
  2. max-width: 100%;: Similar to max-height, but for width. This sets the maximum width of the image to 100% of its container div.

Explanation:

By combining these two properties, the image will effectively shrink to fit within the div while maintaining its original aspect ratio. The image will scale down proportionately, ensuring that no parts are cropped or distorted.

Additional Notes:

  1. If you want to center the image within the div, add the following CSS property:
img {
  ...
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
Copy after login
  1. Alternatively, you can use the object-fit property to achieve similar results, although it may not be supported in all browsers.

The above is the detailed content of How to Fit an Image Snugly 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