CSS background-attachment Property

CSS background-attachment property defines whether the background image should scroll along with the rest of the page or not.

In the example below, the background-attachment property is set to fixed. Therefore, the background image will not scroll along with the page.

Example:

body{
   background-image: url('images/tree.jpg');
   background-repeat: no-repeat;
   background-attachment: fixed;
}

But, If you set the background-attachment property to scroll, the background image will start scrolling along with the page. See the example below:

Example:

body{
   background-image: url('images/tree.jpg');
   background-repeat: no-repeat;
   background-attachment: scroll;
}

Now, suppose you set a background image to <div> element and fixed its height(say 300px) and you want that background image to scroll along with the content of the <div> only, not along with the rest of the page scroll. In such situations, we should use background-attachment: local;. See the example below:

Example:

div{
   background-image: url('images/tree.jpg');
   background-repeat: no-repeat;
   background-attachment: local;
}

CSS Syntax

The background-attachment property has the following syntax:

background-attachment: scroll|fixed|local|initial|inherit;

Property Values

The background-attachment property accepts the following values:

scrollThe background image scrolls along with the page. This is the default value.
fixedThe background image remains fixed relative to the page and it doesn’t scroll along with the page.
localThe background image scrolls along with the element’s content itself. Also the background image scrolls relative to the element, not the page. Scrolling the page has no effect on the background image.
initialSets the background-attachment property to its default value(scroll).
inheritInherits the background-attachment property from the parent element.

General Info

Default Valuescroll
InheritedNo
JavaScript Usageelement.style.backgroundAttachment = “fixed”

Related Pages

CSS Tutorial: CSS Background

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

Leave a Comment