background-attachment

The background-attachment property sets whether the background image will scroll along with the item content.

Initial Value scroll
Applies to All elements, including ::first-letter and ::first-line
Inheritance no
Animation discrete

The background-attachment property specifies whether the background image should be fixed or moved with respect to the screen’s scrolling. If an element in the viewport has a background image, you can choose whether to scroll with it or pin it.

Syntax

/* Keyword values */

background-attachment: scroll;
background-attachment: fixed;
background-attachment: local;

/* Global values */

background-attachment: inherit;
background-attachment: initial;
background-attachment: revert;
background-attachment: unset;

Description

valuewhat it does
scrollDefault value. The background image will scroll along with the rest of the document’s content.
fixedThe background image will be fixed and will not scroll with the rest of the document content.
localThe background image will scroll along with the content of the local element.
inheritThe value is inherited from the parent element.
initialSets the default value.

Example

In this example, we have created two div block elements.

For the first one, we applied styles that allow us to specify the block height (height property), the background image (background-image), specify that it will be static (background-attachment), center it (background-position) and disable the background image repeat (background-repeat).

Note that you can specify all the properties for the background of an element in one declaration using the shorthand property background. The second element is an empty 500px block that will allow us to demonstrate the parallax effect by scrolling the page. You’ll see that the image (the first block) stays in one place and doesn’t scroll with the page.

HTML & CSS

<section class="your-container">
<div class="fixed-bg"></div>
<div style="height: 500px;"></div>
</section>

.fixed-bg {
    height: 350px;
    background-image: url('https://stackdiary.com/wp-content/uploads/2022/10/CSS-Reference.png');
    background-attachment: fixed;
    background-position: center;
    background-repeat: no-repeat;
}