CSS background-size Property

CSS background-size Property

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

selector { background-size: value; }

2. Accepted Values

ValueDescription
auto (default)Keeps the original size of the image.
coverScales the image to cover the entire container while maintaining the aspect ratio.
containScales 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

.box { width: 300px; height: 200px; background-image: url("image.jpg"); background-size: cover; background-position: center; }

✅ The background covers the entire element but may crop parts of the image.

4. Example – Using contain

.box { width: 300px; height: 200px; background-image: url("image.jpg"); background-size: contain; }

✅ The background fits inside the element without cropping but may leave empty space.

5. Example – Using Fixed Dimensions

.box { width: 400px; height: 300px; background-image: url("image.jpg"); background-size: 100px 50px; }

✅ The background image is set to exactly 100px wide and 50px tall.

6. Example – Using Percentage Values

.box { width: 400px; height: 300px; background-image: url("image.jpg"); background-size: 50% 100%; }

✅ 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.

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close