CSS propertyColors and backgrounds
background-attachment
Decides whether the background scrolls with the content or stays in place.
- Initial value
scroll- Inherited
- No
- Animatable
- no
- Applies to
- all elements
- JavaScript
element.style.backgroundAttachment = "fixed"
Example
#CSS
.parallax {
background: url("/img/city.webp") center / cover;
background-attachment: fixed;
}Example HTML
<div style="height: 160px; overflow: auto; border-radius: 12px;">
<div class="parallax" style="height: 120px; background: url('/collections/covers/jak-zostac-programista.webp') center / cover; background-attachment: fixed;"></div>
<p style="margin: 0; padding: 12px; background: #0c0c10;">Scroll: the photo stays in place while the content moves over it.</p>
<p style="margin: 0; padding: 12px; background: #0c0c10;">More content below the photo.</p>
</div>Preview
Definition and usage
#The background-attachment property defines how the background behaves when scrolling. By default (scroll), the background is attached to the element and scrolls with the page.
fixed pins the background to the browser window. The content moves over a stationary image, which gives a parallax effect. local makes the background scroll with the contents of a scrollable element, not with the element itself.
On many phones fixed is ignored or works jerkily, and on desktops it can burden scrolling. Use it sparingly.
Syntax
#Syntax
background-attachment: scroll | fixed | local;Values
#Values in practice
#scroll
The background is attached to the element, not to its scrolling content.
.demo { background-attachment: scroll; }local
The background scrolls with the content inside the element.
.demo { background-attachment: local; }fixed
The background is pinned to the viewport.
.demo { background-attachment: fixed; }Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- On phones the
fixedeffect often does not work. Treat it as an embellishment the page still looks good without. localis useful for shadows that signal scrolling inside lists.
Related entries
#Spotted a mistake or missing an example? Write to us.