Home > Web Front-end > CSS Tutorial > How to Preserve Aspect Ratio While Fitting an Image Within a Div?

How to Preserve Aspect Ratio While Fitting an Image Within a Div?

Barbara Streisand
Release: 2024-11-10 08:43:03
Original
551 people have browsed it

How to Preserve Aspect Ratio While Fitting an Image Within a Div?

Preserving Aspect Ratio While Fitting an Image within a Div

When displaying an image within a restricted space, it's often desirable to fit it without compromising its aspect ratio. HTML and CSS provide an elegant solution to achieve this.

Approach

The key to maintaining the image's aspect ratio is to utilize the max-height and max-width CSS properties. Here's how to implement it:

  1. Set the div height and width: Determine the desired height and width of the div to contain the image.
  2. Apply max-height and max-width to the image:

    • max-height: 100%;: Ensures the image height does not exceed the div's height.
    • max-width: 100%;: Prevents the image width from spilling over the div's width.

By doing so, the image will shrink or expand within the div's boundaries while preserving its aspect ratio.

Example

Consider the following HTML and CSS code:

<div>
Copy after login

In this example, the image "my-image.jpg" will dynamically adjust its size to fit within the 48x48 div, maintaining its original proportions.

The above is the detailed content of How to Preserve Aspect Ratio While Fitting an Image Within a Div?. 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