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-attachment
property in conjunction with thebackground-image
property to specify the source of a background image. - Consider using the
background-attachment
property in combination with media queries to create responsive layouts that adapt to different screen sizes and resolutions. - Avoid using the
background-attachment
property on elements that are frequently updated or animated, as this can impact performance. - Test your use of the
background-attachment
property 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 |