CSS background-size
Property
The background-size
property in CSS controls the size of the background image. It allows you to scale the image to fit its container in different ways.
1. Syntax
2. Accepted Values
Value | Description |
---|---|
auto (default) | Keeps the original size of the image. |
cover | Scales the image to cover the entire container while maintaining the aspect ratio. |
contain | Scales the image to fit inside the container without cropping. |
<length> | Defines a specific width and height (e.g., 100px 50px ). |
<percentage> | Specifies the size relative to the element’s dimensions (50% 100% ). |
3. Example – Using cover
✅ The background covers the entire element but may crop parts of the image.
4. Example – Using contain
✅ The background fits inside the element without cropping but may leave empty space.
5. Example – Using Fixed Dimensions
✅ The background image is set to exactly 100px wide and 50px tall.
6. Example – Using Percentage Values
✅ The width is 50% of the element, and the height is 100%.
7. Best Practices
✔ Use cover
for full background coverage (e.g., hero sections).
✔ Use contain
when you need the whole image visible (e.g., logos).
✔ Combine with background-position
for precise control.
✔ Use percentages for responsive designs.