CSS Background Attachment

The background-attachment property decides whether a background image scrolls with the page or stays fixed in the viewport.

Scroll or fixed

By default a background image scrolls along with its element, so it moves as the page moves. Setting <background-attachment> to <fixed> pins the image to the viewport instead, so the content appears to slide over a stationary background.

A fixed background

<!DOCTYPE html>
<html>
<head>
<style>
body {
  background-image: url('bg.jpg');
  background-attachment: fixed;
}
</style>
</head>
<body>

<h1>Welcome</h1>
<p>Scroll to see the fixed background.</p>

</body>
</html>

The parallax effect

A fixed background is the simplest way to create a subtle parallax look, where a photo stays put while the text scrolls past it. Combine it with no-repeat and a cover size for a full-screen effect.

Full-screen fixed hero

<!DOCTYPE html>
<html>
<head>
<style>
.hero {
  background-image: url('mountains.jpg');
  background-attachment: fixed;
  background-repeat: no-repeat;
  background-size: cover;
}
</style>
</head>
<body>

<div class="hero">
  <h1>Explore the Mountains</h1>
</div>

</body>
</html>
ValueBehavior
scrollImage moves with the element (default)
fixedImage stays fixed to the viewport
localImage scrolls with the element's own content
Note: Fixed backgrounds can feel janky or hurt performance on some mobile browsers. Test on a real device before relying on the effect.
  • Use fixed for a lightweight parallax look
  • Use local when an element has its own scrollbar
  • scroll is the sensible default for most pages