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