Home >Web Front-end >CSS Tutorial >How to Make a Background Image Fit a Div Perfectly Using CSS?
Fitting Background Image to a Div
When placing a background image within a div, it is common to encounter issues where the image is cut off or does not fit properly. To address this problem, CSS offers the background-size property, enabling precise control over the scaling and positioning of the background image.
Scaling the Background Image to Fit Inside the Div
To ensure the background image displays within the div's boundaries without any cropping, set the background-size property to contain:
background-size: contain;
Scaling the Background Image to Cover the Entire Div
Alternatively, to make the background image occupy the entire div, scale it using cover:
background-size: cover;
Visual Demonstration
Consider the following HTML code with a div containing a background image:
<div>
To prevent the image from being cut off, apply the background-size property:
#mainpage { background-size: contain; }
Alternatively, to make the image cover the entire div:
#mainpage { background-size: cover; }
The above is the detailed content of How to Make a Background Image Fit a Div Perfectly Using CSS?. For more information, please follow other related articles on the PHP Chinese website!