background-attachment

Background-attachment controls how the background image is attached to the element’s content. It determines whether the image scrolls with the content or remains fixed in place.

Values

  • scroll (default): The image scrolls with the content. This is the default behavior.
  • fixed: The image remains fixed in place, regardless of the content’s scrolling. It’s attached to the viewport.
  • local: The image scrolls with the content, but only within the element’s boundaries. If the content scrolls beyond the element’s edges, the image stops scrolling.

Usage

You can set the background-attachment property using the following syntax:

background-attachment: scroll | fixed | local;

Example

<div class="fixed-background">
  </div>
.fixed-background {
  background-image: url("your-image.jpg");
  background-attachment: fixed;
}

In this example, the background image will remain fixed in place, even if the content within the .fixed-background div scrolls.

Key Points

  • Viewport: The fixed value attaches the image to the viewport, meaning it stays in place relative to the browser window, regardless of the page’s scrolling.
  • Element Boundaries: The local value attaches the image to the element’s boundaries, so it scrolls with the content within the element but stops when the content reaches the element’s edges.
  • Browser Support: background-attachment is widely supported across modern browsers.

Additional Considerations

  • Compatibility: While background-attachment is well-supported, it’s always a good practice to check for compatibility with older browsers if targeting a wide audience.
  • Performance: Using fixed background images can sometimes impact performance, especially on mobile devices. Consider optimizing your images and using techniques like lazy loading to improve performance.