20. Controlling Background Size and Attachment
When using large background images, you need granular control over how they scale and behave when the user scrolls.
Background Size (background-size)
This property defines how the background image is scaled relative to the container.
| Value | Description |
|---|---|
auto (default) | Displays the image in its original size. |
cover | Scales the image to be as large as possible so that the background area is completely covered by the background image. The image aspect ratio is maintained. (Most common for full-screen headers) |
contain | Scales the image to be as large as possible without cropping or stretching. The image aspect ratio is maintained, but it may leave empty space if the aspect ratios don't match. |
| Dimensions | background-size: 200px 100px; (Width Height) |
css .full-screen-bg { background-image: url('image.jpg'); background-size: cover; /* Ensures the element is always filled */ background-position: center; }
Background Attachment (background-attachment)
This property determines whether the background image scrolls with the content or stays fixed in place.
| Value | Description |
|---|---|
scroll (default) | The background image moves when the page scrolls. |
fixed | The background image stays fixed relative to the viewport. This creates a powerful 'parallax' like effect. |
local | The background image scrolls with the element's content (useful if the element itself has internal scrolling). |
css body { background-image: url('stars.jpg'); background-attachment: fixed; /* Creates a fixed, non-moving background */ background-size: cover; }