"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Resize Images While Maintaining Aspect Ratio Using CSS?

How Can I Resize Images While Maintaining Aspect Ratio Using CSS?

Published on 2025-01-21
Browse:508

How Can I Resize Images While Maintaining Aspect Ratio Using CSS?

Force Image Resize while Maintaining Aspect Ratio

When working with images, it's often necessary to resize images to specific dimensions. However, preserving the aspect ratio ensures that images don't appear distorted or stretched.

Initial Attempt:

Initially, specified dimensions and custom CSS rules were used to resize the image, but the aspect ratio was not maintained:

img {
  max-width: 500px;
}

Solution:

To force image resize while preserving the aspect ratio, the following CSS properties can be used:

  • display: block;: Ensures the image can flow within the page content.
  • max-width:230px;: Sets the maximum width of the image.
  • max-height:95px;: Sets the maximum height of the image.
  • width: auto;: Allows the image to automatically fill the available space within the max-width and max-height constraints.
  • height: auto;: Automatically adjusts the height based on the image's inherent aspect ratio.

Result:

Applying these CSS rules to the image:

This image is originally 400x400 pixels, but should get resized by the CSS:

How Can I Resize Images While Maintaining Aspect Ratio Using CSS?
img {
  display: block;
  max-width:230px;
  max-height:95px;
  width: auto;
  height: auto;
}

Results in an image that is resized within the specified maximum dimensions while maintaining its original aspect ratio.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3