Home > Article > Web Front-end > How can I scale an image to fit a bounding box in CSS while maintaining its aspect ratio?
Scale Image to Fit a Bounding Box
Scaling an image proportionally within a bounding box using only CSS seems like a straightforward task. However, this approach falls short when the desired outcome is to enlarge the image until it fully fills one dimension of the bounding box.
CSS-Only Solution
Fortunately, CSS3 offers a solution to this dilemma. By leveraging the background-image and background-size properties, you can scale images within bounding boxes as needed.
Implementation
To implement this solution, follow these steps:
Example
<code class="html"><div class="bounding-box"> <!-- Image as background-image --> </div></code>
<code class="css">.bounding-box { background-image: url(...); background-size: contain; }</code>
Additional Considerations
<code class="css">.bounding-box { position: absolute; background-position: center; }</code>
By embracing these CSS techniques, you can effectively scale images to fill bounding boxes while maintaining their original proportions.
The above is the detailed content of How can I scale an image to fit a bounding box in CSS while maintaining its aspect ratio?. For more information, please follow other related articles on the PHP Chinese website!