CSS background-attachment

The background-attachment property in CSS specifies whether a background image scrolls with the rest of the page, is fixed, or scrolls within the content area of an element. This property enhances the user experience by allowing creative designs like parallax effects or fixed backgrounds.


Syntax of background-attachment

</>
Copy
background-attachment: scroll | fixed | local | initial | inherit;

Values

ValueDescription
scrollThe background image scrolls along with the page content. This is the default value.
fixedThe background image is fixed with regard to the viewport and does not move when the page is scrolled.
localThe background image scrolls along with the element’s content. If the content is scrolled, the background moves as well.
initialSets the property to its default value (scroll).
inheritInherits the value from its parent element.

Default Value

scroll


Examples for background-attachment

Using the CSS background-attachment Property

The following examples demonstrate how the background-attachment property can be used to achieve different effects.

</>
Copy
/* Default: scroll */
.element {
  background-image: url('example.jpg');
  background-attachment: scroll;
}

/* Fixed background */
.element {
  background-image: url('example.jpg');
  background-attachment: fixed;
}

/* Local scrolling */
.element {
  background-image: url('example.jpg');
  background-attachment: local;
}

Example for Fixed Background

Below is an example of how the background-attachment: fixed property creates a parallax effect, where the background image remains fixed while the content scrolls.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
<style>
  body {
    margin: 0;
    font-family: Arial, sans-serif;
  }

  .parallax {
    background-image: url('https://www.tutorialkart.com/img/mountains.jpg');
    background-attachment: fixed;
    background-size: cover;
    background-position: center;
    height: 600px;
    color: white;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 24px;
  }

  .content {
    padding: 20px;
    font-size: 18px;
    text-align: center;
  }
</style>
</head>
<body>

<div class="parallax">Parallax Background</div>

<div class="content">
  <p>Scroll to see the parallax effect!</p>
  <p>This example uses background-attachment: fixed; to create the effect.</p>
</div>

</body>
</html>

Browser Support

The background-attachment property is widely supported across modern browsers. Below is a compatibility table:

BrowserVersion
Chrome1.0
Edge4.0
Firefox1.0
Safari1.0
Opera3.5