📌 Introduction
The background-attachment property in CSS controls how a background image behaves when the page is scrolled. It determines whether the background scrolls with the page, stays fixed, or scrolls relative to the element's content. This is especially useful for creating **parallax effects**, fixed hero backgrounds, or scroll-based UI designs. 🎨✨
🎯 What Does background-attachment Do?
- Controls background behavior during scroll
- Creates parallax-like effects
- Defines how backgrounds behave relative to viewport or content
- Works with images, gradients, and multiple layers
✨ Syntax
Syntax
selector {
background-attachment: scroll | fixed | local;
}🧩 Available Values
1. scroll (default)
The background image moves **along with the page**. This is the default behavior of most elements.
scroll
background-attachment: scroll;2. fixed
The background image stays **fixed to the viewport**, even when scrolling. This creates the classic **parallax scrolling effect**.
fixed
background-attachment: fixed;Note
3. local
The background scrolls with the element’s **content**, not the entire page. Useful for scrollable containers.
local
background-attachment: local;🔥 Practical Examples
1. Parallax Hero Section (fixed)
Parallax Effect
.hero {
background-image: url("hero.jpg");
background-size: cover;
background-position: center;
background-attachment: fixed;
height: 400px;
}2. Normal Scrolling Background (scroll)
Default Scrolling
.normal {
background-image: url("pattern.png");
background-repeat: repeat;
background-attachment: scroll;
}3. Scrollable Container Background (local)
Local Scroll Example
.scroll-box {
width: 300px;
height: 200px;
overflow: auto;
background-image: url("bg.jpg");
background-attachment: local;
}🧩 Using Multiple Background Layers
Each background layer can have its own background-attachment value.
Multiple Layers
background-image: url("layer1.png"), url("layer2.png");
background-attachment: fixed, scroll;📊 Summary Table
| Value | Behavior | Use Case |
|---|---|---|
| scroll | Background moves with page scroll | Default, patterns, normal layouts |
| fixed | Background stays fixed to viewport | Parallax, hero sections |
| local | Background moves with element content | Scrollable UI sections |
🖼️ Visual Demo
Further details can be found at: https://dummyimage.com/900x260/eeeeee/000000&text=background-attachment+demo
🎉 Conclusion
The background-attachment property is simple but incredibly powerful. Whether you want a fixed parallax background, a normal scrolling background, or a scrollable UI container with dynamic backgrounds—this property gives you precise control. Master it to create modern, engaging, and visually immersive designs. 🚀