Home  >  Article  >  Web Front-end  >  How to Scale an Image to Fill a Bounding Box While Preserving Aspect Ratio in CSS?

How to Scale an Image to Fill a Bounding Box While Preserving Aspect Ratio in CSS?

Barbara Streisand
Barbara StreisandOriginal
2024-10-27 04:26:29814browse

How to Scale an Image to Fill a Bounding Box While Preserving Aspect Ratio in CSS?

Scaling an Image to Fill a Bounding Box Preserving Aspect Ratio

Scaling an image to fit within a bounding box while maintaining its aspect ratio can pose a challenge in CSS.

Consider the following use cases:

  • Use Case 1: Image larger than container.
  • Use Case 2: Image smaller than container (scale down).
  • Use Case 3: Image smaller than container (scale up).

The standard CSS properties max-width and max-height only work when the image is larger than the container (Use Case 1 and 2).

Fortunately, CSS3 offers a solution for Use Case 3. By setting the image as a background image and using the background-size property with the contain value, the image can be scaled up to fill the container without distorting its aspect ratio.

HTML:

<div class='bounding-box'>
</div>

CSS:

.bounding-box {
  background-image: url(...);
  background-repeat: no-repeat;
  background-size: contain;
}

To center the image within the container:

.bounding-box {
  background-image: url(...);
  background-size: contain;
  position: absolute;
  background-position: center;
  background-repeat: no-repeat;
  height: 100%;
  width: 100%;
}

This solution is compatible with most modern browsers.

The above is the detailed content of How to Scale an Image to Fill a Bounding Box While Preserving Aspect Ratio in CSS?. 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