CSS

background-attachment


The background-attachment property in CSS is used to specify whether a background image is fixed within the viewport or scrolls with the rest of the content. This property can enhance the visual experience of your website by creating a more dynamic and engaging design.

 

Values for background-attachment

 

1. scroll

The background image scrolls with the rest of the content. This is the default value.

.example1 {
    background-image: url('background.png');
    background-attachment: scroll;
}

 

2. fixed

 The background image is fixed relative to the viewport. It does not move when the content is scrolled.

.example2 {
    background-image: url('background.png');
    background-attachment: fixed;
}

 

3. local

 The background image scrolls with the content of the element that contains it, instead of the entire page.

.example3 {
    background-image: url('background.png');
    background-attachment: local;
}

 

Example 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Background Attachment Example</title>
    <style>
        body {
            font-family: Arial, sans-serif;
        }
        h2 {
            margin-top: 20px;
        }
        .attachment-example {
            width: 300px;
            height: 200px;
            background-image: url('background.png');
            background-repeat: no-repeat;
            background-size: cover;
            border: 1px solid #000;
            margin-bottom: 20px;
        }
        .scroll-container, .fixed-container, .local-container {
            height: 500px;
            overflow: auto;
            border: 1px solid #ccc;
        }
        .content {
            height: 1000px;
        }
    </style>
</head>
<body>
    <h2>Scroll</h2>
    <div class="scroll-container">
        <div class="attachment-example" style="background-attachment: scroll;"></div>
        <div class="content"></div>
    </div>

    <h2>Fixed</h2>
    <div class="fixed-container">
        <div class="attachment-example" style="background-attachment: fixed;"></div>
        <div class="content"></div>
    </div>

    <h2>Local</h2>
    <div class="local-container">
        <div class="attachment-example" style="background-attachment: local;"></div>
        <div class="content"></div>
    </div>
</body>
</html>

In this example, replace 'background.png' with the actual path to your background image. This will create three boxes demonstrating the different values of the background-attachment property. Each box has a container with scrolling content to show how the background behaves with scrolling.