Background-size controls the size of a background image within its container element. It offers flexibility in scaling and positioning images.
Syntax
background-size: <value1> <value2>;
Values
value1 and value2: Can be either keywords or lengths.
Keywords:
contain: Scales the image to fit within the container while preserving its aspect ratio.cover: Scales the image to cover the entire container while maintaining its aspect ratio.auto: Scales the image to fit the container’s width or height, depending on which is smaller.
Lengths:
length: Specifies the exact width and height of the image, using units likepx,em,rem,%, etc.
Examples
- Scaling to fit the container:
background-size: contain;
- Covering the entire container:
background-size: cover;
- Scaling to fit the width:
background-size: auto 100%;
- Scaling to fit the height:
background-size: 100% auto;
- Specifying exact dimensions:
background-size: 300px 200px;
Additional Considerations
- Multiple background images: If you have multiple background images, the
background-sizeproperty applies to each individually. - Background-position: The
background-positionproperty determines where the background image is placed within its container. - Background-repeat: The
background-repeatproperty controls whether the background image is repeated or not.
Best Practices
- Choose the most appropriate value based on your design goals and the image’s dimensions.
- Consider the aspect ratio of the image to prevent distortion.
- Experiment with different values to achieve the desired effect.