background-attachment
Definition
The background-attachment property in CSS is used to control how a background image is positioned within an element.
Examples
Setting a background image to scroll with the rest of the content on the page:
.scrolling-background {
background-image: url('image.jpg');
background-attachment: scroll;
}
Setting a background image to be fixed in place:
.fixed-background {
background-image: url('image.jpg');
background-attachment: fixed;
}
Setting a background image to scroll with an element itself, but not with the rest of the page:
.local-background {
background-image: url('image.jpg');
background-attachment: local;
}
Values
| Value | Description |
|---|---|
scroll | The background image will scroll with the rest of the content on the page. |
fixed | The background image will remain fixed in place and will not scroll with the rest of the content on the page. |
local | The background image will scroll with the element itself, but not with the rest of the page. |
Best Practices
- Use the
background-attachmentproperty in conjunction with thebackground-imageproperty to specify the source of a background image. - Consider using the
background-attachmentproperty in combination with media queries to create responsive layouts that adapt to different screen sizes and resolutions. - Avoid using the
background-attachmentproperty on elements that are frequently updated or animated, as this can impact performance. - Test your use of the
background-attachmentproperty in different browsers to ensure that it works as expected.
Browser Compatibility
| Chrome | Firefox | Safari | Internet Explorer | Microsoft Edge | Opera |
|---|---|---|---|---|---|
| Yes | Yes | Yes | Mo | Yes | Yes |