0
0
CssHow-ToBeginner · 3 min read

How to Set Background Attachment in CSS: Simple Guide

Use the background-attachment CSS property to control whether a background image scrolls with the page or stays fixed. Set it to scroll (default) to move with content, or fixed to keep it in place while scrolling.
📐

Syntax

The background-attachment property accepts these main values:

  • scroll: The background moves when you scroll the page (default).
  • fixed: The background stays fixed in place and does not move when scrolling.
  • local: The background scrolls with the element's content, useful for scrollable elements.
css
background-attachment: scroll | fixed | local;
💻

Example

This example shows a fixed background image that stays in place while the page content scrolls over it.

css
body {
  background-image: url('https://via.placeholder.com/800x600');
  background-repeat: no-repeat;
  background-size: cover;
  background-attachment: fixed;
  margin: 0;
  height: 200vh; /* Make page tall to enable scrolling */
}

h1 {
  margin: 40px;
  color: white;
  text-shadow: 1px 1px 2px black;
}
Output
A tall page with a large background image that stays fixed in place while the text scrolls over it.
⚠️

Common Pitfalls

Common mistakes include:

  • Not setting a height or enough content to see the scrolling effect.
  • Using background-attachment: fixed on mobile devices where it may not work well or cause performance issues.
  • Forgetting to set background-repeat or background-size, which can cause the image to tile or appear too small.
css
/* Wrong: no scrolling effect visible */
body {
  background-image: url('https://via.placeholder.com/800x600');
  background-attachment: fixed;
  margin: 0;
  height: 100vh; /* Not tall enough to scroll */
}

/* Right: tall page to see fixed background effect */
body {
  background-image: url('https://via.placeholder.com/800x600');
  background-attachment: fixed;
  background-repeat: no-repeat;
  background-size: cover;
  margin: 0;
  height: 200vh;
}
📊

Quick Reference

ValueDescription
scrollBackground scrolls with the page content (default)
fixedBackground stays fixed in place when scrolling
localBackground scrolls with the element's content

Key Takeaways

Use background-attachment to control if background images scroll or stay fixed.
The default value is scroll, which moves the background with the page.
Fixed backgrounds stay in place but may have issues on some mobile browsers.
Ensure enough page height to see scrolling effects with fixed backgrounds.
Combine with background-repeat and background-size for best visual results.