How to Make Background Fixed on Scroll in CSS
To make a background fixed on scroll in CSS, use the
background-attachment: fixed; property on the element with the background. This keeps the background image in place while the content scrolls over it.Syntax
The CSS property background-attachment controls how the background image behaves when the page scrolls.
fixed: The background stays fixed in place and does not move when scrolling.scroll: The background moves along with the content (default behavior).local: The background scrolls with the element's content.
css
selector {
background-image: url('image.jpg');
background-attachment: fixed;
background-size: cover;
}Example
This example shows a full-page background image that stays fixed while you scroll the text content.
css
html, body {
height: 100%;
margin: 0;
}
body {
background-image: url('https://via.placeholder.com/800');
background-attachment: fixed;
background-repeat: no-repeat;
background-size: cover;
font-family: Arial, sans-serif;
color: white;
padding: 20px;
}
.content {
height: 150vh; /* taller than viewport to enable scrolling */
background-color: rgba(0, 0, 0, 0.5); /* semi-transparent overlay for readability */
padding: 20px;
border-radius: 8px;
}Output
<body> with a fixed background image that stays in place while the text scrolls over a semi-transparent dark overlay.</body>
Common Pitfalls
Some common mistakes when using background-attachment: fixed; include:
- Not setting a background image, so the fixed effect is not visible.
- Using
background-attachment: fixed;on elements inside containers withoverflow: autooroverflow: scroll, which can prevent the fixed background from working properly. - Forgetting to set
background-sizetocoveror appropriate size, causing the image to repeat or not fill the area.
Example of wrong and right usage:
css
/* Wrong: fixed background inside a scrolling div */ .scroll-box { height: 200px; overflow: auto; background-image: url('https://via.placeholder.com/400'); background-attachment: scroll; background-size: cover; } /* Right: fixed background on body or html element */ body { background-image: url('https://via.placeholder.com/400'); background-attachment: fixed; background-size: cover; }
Quick Reference
Background Attachment Values:
fixed: Background stays fixed on screen during scroll.scroll: Background scrolls with content (default).local: Background scrolls with element's content.
Use background-size: cover; to make the background image cover the entire element area.
Key Takeaways
Use
background-attachment: fixed; to keep background images fixed during scroll.Apply fixed backgrounds on the
body or html elements for best results.Avoid using fixed backgrounds inside elements with scrolling containers (
overflow set).Combine with
background-size: cover; to fill the area nicely.Test on different browsers as some mobile browsers may not fully support fixed backgrounds.