CSS
🎯 What is background-attachment?
The background-attachment property defines the scrolling behavior of a background image.
🧩 Simple Definition
background-attachment = controls how a background image behaves during scrolling
🧩 Basic Syntax
background-attachment: value;
🧩 Accepted Values
| Value | Description |
|---|---|
| scroll | Background moves with the page |
| fixed | Background stays fixed while scrolling |
| local | Background scrolls with the element’s content |
| initial | Resets to default value |
| inherit | Inherits value from parent element |
🔹 scroll (Default Value)
background-attachment: scroll;
👉 The background image moves together with the page content.
This is the default browser behavior.
🧩 Example
div {
background-image: url("background.jpg");
background-attachment: scroll;
}
📘 Result
When the user scrolls the page, the background image also moves.
🔹 fixed
background-attachment: fixed;
👉 The background image stays fixed in one position.
Even when the page scrolls, the image does not move.
🧩 Example
body {
background-image: url("wallpaper.jpg");
background-attachment: fixed;
}
📘 Result
The background behaves like wallpaper pinned to the screen.
This effect is commonly used in:
- parallax scrolling
- hero sections
- modern landing pages
🔹 local
background-attachment: local;
👉 The background scrolls together with the element’s own content.
This is especially useful for scrollable containers.
🧩 Example
div {
background-image: url("background.jpg");
background-attachment: local;
overflow: scroll;
}
📘 Result
The background moves only when the content inside the element is scrolled.
⚖️ Difference Between scroll, fixed, and local
| Value | Behavior |
|---|---|
| scroll | Background moves with the page |
| fixed | Background stays fixed |
| local | Background moves with the element’s content |
🧩 Practical Example
.hero {
background-image: url("hero.jpg");
background-size: cover;
background-position: center;
background-repeat: no-repeat;
background-attachment: fixed;
}
🧠 Explanation
background-size: cover
Makes the image fill the entire area.
background-position: center
Centers the image.
background-repeat: no-repeat
Prevents repetition.
background-attachment: fixed
Keeps the image fixed during scrolling.
🎨 Common Use Cases
The background-attachment property is commonly used for:
- fullscreen backgrounds
- parallax effects
- hero sections
- modern landing pages
- scrollable containers
⚠️ Important Note
Using background-attachment: fixed; may affect performance on some mobile devices and older browsers.
For responsive websites, always test scrolling performance across devices.
