CSS Background Attachment
The background-attachment
property determines whether the background image scrolls with the page or remains fixed. A fixed background can create a parallax effect, giving your site a more dynamic and engaging appearance.
Key Topics
Scroll
background-attachment: scroll;
is the default behavior. The image moves as the user scrolls down the page.
Fixed
background-attachment: fixed;
keeps the image in place while the foreground content scrolls, creating a subtle parallax-like effect.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" >
<meta name="viewport" content="width=device-width, initial-scale=1.0" >
<title>Fixed Background Example</title>
<style>
body {
background-image: url('scenic.jpg');
background-repeat: no-repeat;
background-size: cover;
background-attachment: fixed;
font-family: Arial, sans-serif;
color: #fff;
margin: 0;
}
h1 {
text-align: center;
padding: 100px 20px;
background: rgba(0,0,0,0.5);
}
p {
max-width: 600px;
margin: 20px auto;
padding: 20px;
background: rgba(0,0,0,0.5);
line-height: 1.5;
}
</style>
</head>
<body>
<h1>Fixed Background Heading</h1>
<p>As you scroll, the background image remains in place while the text moves. This creates an immersive effect, making the background feel more dynamic.</p>
<p>Keep scrolling to experience the effect further.</p>
<p>This technique can enhance visual storytelling on your webpage.</p>
</body>
</html>
Explanation: The fixed background remains static while text and other elements scroll over it, producing a distinctive visual effect that can emphasize the content against a stable backdrop.
Local
background-attachment: local;
makes the background scroll with the element’s content. This is less common but can be useful for scrollable containers with their own backgrounds.
Key Takeaways
- Scroll (default): Background moves with the page.
- Fixed: Background stays in place, creating a striking visual effect.
- Local: Background moves with the element’s scrollable container.