🌄 CSS background-attachment
: Controlling Background Image Scrolling Behavior
Background images add depth and style to web pages. But how these images behave when the user scrolls can dramatically affect the visual experience. The CSS background-attachment
property lets you control whether the background image scrolls with the page content or stays fixed in place.
🧾 What is background-attachment
?
The background-attachment
property specifies whether a background image is fixed relative to the viewport or scrolls along with the containing element.
🧬 Syntax
selector {
background-attachment: scroll | fixed | local | initial | inherit;
}
🔍 Property Values
Value | Description |
---|---|
scroll | The default. Background scrolls with the element’s content. |
fixed | Background stays fixed relative to the viewport — it does not move when scrolling the page. |
local | Background scrolls with the element’s content including its scrollable content (e.g., inside a scrollable div). |
initial | Resets the property to the default (scroll ). |
inherit | Inherits the property from its parent element. |
🎯 Examples
1. Scroll background (default behavior)
body {
background-image: url('mountains.jpg');
background-attachment: scroll;
}
The background moves up and down as the user scrolls the page.
2. Fixed background (parallax effect)
header {
background-image: url('sky.jpg');
background-attachment: fixed;
background-size: cover;
}
The background image stays fixed while content scrolls over it, creating a parallax-like effect.
3. Local background in scrollable container
div.scrollable {
height: 200px;
overflow: auto;
background-image: url('texture.png');
background-attachment: local;
}
The background scrolls along with the content inside the scrollable div.
🛠️ When to Use
- Use
fixed
to create immersive, modern parallax scrolling effects. - Use
scroll
for traditional background behavior. - Use
local
when applying backgrounds to elements with their own scrollbars and you want the background to scroll with the content.
✅ Browser Support and Considerations
- All modern browsers support these values.
fixed
backgrounds may behave differently on mobile browsers due to performance optimizations.- Using large fixed background images can impact performance; optimize image size.
🔚 Conclusion
The CSS background-attachment
property is a simple yet powerful way to control how background images behave when users scroll your page. Whether you want dynamic scrolling backgrounds or fixed immersive scenes, this property helps you achieve stunning visual effects.