CSS

🎯 What is background-attachment?

The background-attachment property defines the scrolling behavior of a background image.

🧩 Simple Definition

CSS
background-attachment = controls how a background image behaves during scrolling

🧩 Basic Syntax

CSS
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)

CSS
background-attachment: scroll;

👉 The background image moves together with the page content.

This is the default browser behavior.

🧩 Example

CSS

div {

  background-image: url("background.jpg");

  background-attachment: scroll;

}
                

📘 Result

When the user scrolls the page, the background image also moves.

🔹 fixed

CSS
background-attachment: fixed;

👉 The background image stays fixed in one position.

Even when the page scrolls, the image does not move.

🧩 Example

CSS

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

CSS
background-attachment: local;

👉 The background scrolls together with the element’s own content.

This is especially useful for scrollable containers.

🧩 Example

CSS

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

CSS

.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.