Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Set the Background Attachment with CSS
The background-attachment property controls whether a background image scrolls with the content or remains fixed in the viewport. This CSS property is useful for creating parallax effects or keeping decorative backgrounds stationary.
Syntax
background-attachment: value;
Property Values
| Value | Description |
|---|---|
scroll |
Background scrolls with content (default) |
fixed |
Background stays fixed in viewport |
local |
Background scrolls with element's content |
Example: Fixed Background
This example demonstrates a fixed background that remains stationary while content scrolls:
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-image: url('/css/images/css.jpg');
background-repeat: no-repeat;
background-attachment: fixed;
background-size: cover;
margin: 0;
padding: 20px;
height: 200vh;
}
.content {
background-color: rgba(255, 255, 255, 0.9);
padding: 20px;
margin: 20px 0;
border-radius: 5px;
}
</style>
</head>
<body>
<div class="content">
<p>The background image is fixed. Try scrolling down the page.</p>
<p>Notice how the background stays in place while content moves.</p>
</div>
<div class="content">
<p>This creates a parallax-like effect.</p>
<p>The background remains stationary in the viewport.</p>
</div>
<div class="content">
<p>Keep scrolling to see the effect.</p>
<p>The background-attachment: fixed property makes this possible.</p>
</div>
</body>
</html>
Example: Scrolling Background
By default, backgrounds scroll with the content using background-attachment: scroll:
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-image: url('/css/images/css.jpg');
background-repeat: no-repeat;
background-attachment: scroll;
background-size: cover;
margin: 0;
padding: 20px;
height: 200vh;
}
.content {
background-color: rgba(255, 255, 255, 0.8);
padding: 15px;
margin: 15px 0;
}
</style>
</head>
<body>
<div class="content">
<p>With scroll attachment, the background moves with content.</p>
</div>
<div class="content">
<p>This is the default behavior for background images.</p>
</div>
</body>
</html>
Browser Support
The background-attachment property is supported in all modern browsers. However, fixed backgrounds may have performance implications on mobile devices and are sometimes disabled by mobile browsers.
Conclusion
Use background-attachment: fixed to create stationary backgrounds that remain in place while content scrolls. This property is perfect for creating visual effects and improving page aesthetics.
