Home > Web Front-end > CSS Tutorial > How to Achieve 100% Width or Height While Maintaining Aspect Ratio in CSS?

How to Achieve 100% Width or Height While Maintaining Aspect Ratio in CSS?

Susan Sarandon
Release: 2024-10-29 04:42:02
Original
702 people have browsed it

How to Achieve 100% Width or Height While Maintaining Aspect Ratio in CSS?

Achieving 100% Width or Height While Maintaining Aspect Ratio in CSS

In CSS, setting width: 100% and leaving height set to auto (or vice versa) is often used to constrain an image. However, this can result in the image being disproportionately wide or tall.

To maintain the aspect ratio while constraining the image, consider the following approaches:

Constrain and Crop Using a DIV:

Nest the image within a DIV and set its max-width, max-height, and overflow: hidden. This will prevent the image from exceeding the specified dimensions and crop any excess.

Preserve Aspect Ratio and Limit Maximum Dimensions:

Use the max-width and max-height properties without specifying minimum dimensions. This allows the image to retain its aspect ratio while ensuring it doesn't grow larger than the maximum dimensions specified.

Example Code:

<code class="css">.image-container {
  max-width: 500px;
  max-height: 500px;
  overflow: hidden;
}

.image {
  width: 100%;
  height: auto;
}</code>
Copy after login

This code ensures that the image within the .image-container will not exceed 500px in either width or height while maintaining its original aspect ratio.

The above is the detailed content of How to Achieve 100% Width or Height While Maintaining Aspect Ratio in CSS?. 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