Home > Web Front-end > CSS Tutorial > How Can I Resize Images in HTML While Preserving Aspect Ratio?

How Can I Resize Images in HTML While Preserving Aspect Ratio?

Patricia Arquette
Release: 2024-12-24 16:04:10
Original
921 people have browsed it

How Can I Resize Images in HTML While Preserving Aspect Ratio?

Preserving Aspect Ratio during Image Resizing

When working with images, it's crucial to maintain their aspect ratios to ensure they appear correctly. However, specifying both width and height attributes in HTML often leads to distortions.

Consider the following HTML code:

<img src="big_image.jpg" width="900" height="600" alt="" />
Copy after login

To resize the image while preserving its aspect ratio, apply the following CSS rule:

img {
    display: block;
    max-width: 500px;
}
Copy after login

The display: block; property ensures the image behaves like a block element, allowing it to fill the width of its container. The max-width property sets the maximum width for the image, ensuring it doesn't exceed that width while preserving its height.

This CSS also applies to the following HTML:

<p>This image is originally 400x400 pixels, but should get resized by the CSS:</p>
<img width="400" height="400" src="https://i.sstatic.net/aEEkn.png" />
Copy after login

Using this approach, images of different dimensions will be resized proportionately, preserving their aspect ratios while adhering to the specified maximum width.

The above is the detailed content of How Can I Resize Images in HTML 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