Background

background-attachment

background-attachment sets whether a background image is placed against the element’s border, its contents, or the viewport, and so how it moves when you scroll.

Syntax

<attachment>#

Preview

1. The quick brown fox2. The quick brown fox3. The quick brown fox4. The quick brown fox5. The quick brown fox6. The quick brown fox7. The quick brown fox8. The quick brown fox9. The quick brown fox10. The quick brown fox11. The quick brown fox12. The quick brown fox13. The quick brown fox14. The quick brown fox15. The quick brown fox16. The quick brown fox
Presets
Drag the bottom-right corner to resize

Code

.box {
  overflow: auto;
  background-image: linear-gradient(#88d1c7, #77a7d7, #eaac3a);
  background-attachment: local;
}

Controls

background-attachmentlocal
background-attachment
1. The quick brown fox2. The quick brown fox3. The quick brown fox4. The quick brown fox5. The quick brown fox6. The quick brown fox7. The quick brown fox8. The quick brown fox9. The quick brown fox10. The quick brown fox11. The quick brown fox12. The quick brown fox13. The quick brown fox14. The quick brown fox15. The quick brown fox16. The quick brown fox

About

Values

  • scroll: the initial value. The background is placed against the element’s border. It moves with the element when the page scrolls, but stays put when the element’s own contents scroll.
  • local: the background is placed against the element’s contents (the whole scrollable area) and moves with them when the element scrolls.
  • fixed: the background is placed against the viewport and stays put when the page scrolls, so the element works like a window onto a background fixed to the screen.

When to use it

  • Use local when the background of a scrolling box should scroll along with its text.
  • Use fixed for a background photo that stays still while the page scrolls past it.

Things to watch

  • The background shorthand resets background-attachment, so write it after the shorthand.
  • Safari on iPhone and iPad ignores fixed and shows the background as with scroll.
  • With several background layers, give one value per layer separated by commas, such as local, scroll (the control on this page sets a single value).

In the preview, supporting declarations make the box scrollable (overflow: auto) and give it a top-to-bottom gradient. The box holds lines about twice as tall as itself. With scroll the gradient fits the height of the box; with local it stretches to the height of the contents and moves with the text when you scroll inside the box. With fixed you see part of a gradient as tall as the screen.

Comments