CSS Background Size
The background-size property specifies the size of the background images. It allows you to control how the image scales within its container, which is crucial for responsive design.
Keywords: Cover vs Contain
Two of the most powerful values for background-size are keywords:
- cover: Scales the image to be as large as possible so that the background area is completely covered by the background image. Some parts of the image may be cropped.
- contain: Scales the image to the largest size such that both its width and its height can fit inside the content area. The whole image is shown, but there may be empty space.
Length and Percentages
You can also provide exact values:
background-size: 300px 100px; sets the width to 300px and height to 100px. If you only provide one value (e.g., 50%), the second value is set to auto, preserving the aspect ratio.
Best Practices
For full-screen hero images, background-size: cover combined with background-position: center is the standard solution. This ensures the image covers the screen on both mobile and desktop without distortion.
