Background Attachment
The background-attachment property controls whether a background image scrolls with the page or stays fixed.
The most commonly used values are scroll and fixed.
Background Attachment Flow
Example 1: Scroll
The scroll value makes the background image move along with the element when the page is scrolled.
CSS Code
div {
background-image: url("https://images.unsplash.com/photo-1498050108023-c5249f4df085?auto=format&fit=crop&w=1200&q=80");
background-attachment: scroll;
background-size: cover;
background-position: center;
background-repeat: no-repeat;
min-height: 280px;
}
Output
Example 2: Fixed
The fixed value keeps the background image fixed relative to the viewport while the page content scrolls.
CSS Code
div {
background-image: url("https://images.unsplash.com/photo-1516321318423-f06f85e504b3?auto=format&fit=crop&w=1200&q=80");
background-attachment: fixed;
background-size: cover;
background-position: center;
background-repeat: no-repeat;
min-height: 280px;
}
Output
Example 3: Local
The local value allows the background image to scroll with the element's content.
CSS Code
div {
background-image: url("https://images.unsplash.com/photo-1518770660439-4636190af475?auto=format&fit=crop&w=1200&q=80");
background-attachment: local;
background-size: cover;
background-position: center;
background-repeat: no-repeat;
min-height: 280px;
}
Output
Background Attachment Values
| Value | Behavior |
|---|---|
scroll
|
Background image scrolls with the element. |
fixed
|
Background image stays fixed relative to the viewport. |
local
|
Background image scrolls with the element's content. |
Simple Explanation
scroll → Background moves when the page scrolls.
fixed → Background stays fixed while the page content moves.
local → Background scrolls with the element's content.
Summary
-
Use
background-attachmentto control background scrolling behavior. -
scrollmoves the background with the page. -
fixedkeeps the background fixed. -
localscrolls the background with element content.