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
Patricia ArquetteOriginal
2024-12-24 16:04:10860browse

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="" />

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

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

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" />

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!

Statement:
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