In CSS, setting a background image with its width equal to the page width and height set to maintain the image's proportion can pose challenges, especially when it comes to vertical cropping and image placement.
CSS3 offers the background-size property, which allows for control over the image's size. By setting background-size: cover, you can scale the image to the smallest size that fully covers the background positioning area while maintaining the aspect ratio.
body { background-image: url(images/background.svg); background-size: cover; /* <------ */ background-repeat: no-repeat; background-position: center center; /* optional, center the image */ }
This setting ensures that the background image covers the page's width, and its height is scaled accordingly, resulting in the desired responsiveness and cropping behavior.
The background-size property offers two additional values, contain and cover, which provide different scaling behavior:
Consider the image below displayed within a bounding box. contain ensures the image is fully visible within the box, while cover fills the box with the image, resulting in cropping at the bottom:
[Image of image with contain and cover background-size settings]
The following code demonstrates the difference between contain and cover:
<div><div class="contain"></div> <p>Note the grey background. The image does not cover the whole region, but it's fully contained.</p> </div> <div><div class="cover"></div> <p>Note the ducks/geese at the bottom of the image. Most of the water is cut, as well as a part of the sky. You don't see the complete image anymore, but neither do you see any background color; the image covers all of the <code><div></code>.</p> </div>
The above is the detailed content of How Can I Make a CSS Background Image Fit the Width and Proportionally Auto-Scale the Height?. For more information, please follow other related articles on the PHP Chinese website!