Want a fixed background that stays put while scrolling? background-attachment: fixed
in CSS often fails in mobile browsers. Here's a workaround, a "hack," to achieve this effect.
Let's examine the issue with two background types: linear gradients and images.
For a fixed gradient on scroll, we might use this CSS:
body { background: linear-gradient(335deg, rgba(255,140,107,1) 0%, rgba(255,228,168,1) 100%); background-attachment: fixed; background-position: center; background-repeat: no-repeat; height: 100vh; }
On Android Chrome and Firefox, the gradient scrolls, then jumps. This seems related to the browser's difficulty re-rendering the gradient in real-time when the URL bar hides/appears. iOS Safari exhibits similar behavior.
The problem is the same with images:
body { background: url(../assets/test_pic.jpg); background-repeat: no-repeat; background-size: cover; background-position: center; background-attachment: fixed; height: 100vh; }
background-attachment: fixed
also ignores the height
property, calculating position relative to the viewport, not the element's height. This might be because background-attachment: fixed
uses the smallest viewport, while elements use the largest. Viewport units (vh) don't resize when the URL bar changes visibility.
caniuse
highlights browser inconsistencies with background-attachment: fixed
.
The solution involves removing background-attachment: fixed
and using separate elements. If background-attachment: fixed
uses the smallest viewport, let's use an element that uses the largest.
Create two divs: one for the background and one for content:
<div class="bg"></div> <div class="content"> <!-- Your content here --> </div>
Style them like this:
.bg { background: linear-gradient(335deg, rgba(255,140,107,1) 0%, rgba(255,228,168,1) 100%); background-repeat: no-repeat; background-position: center; height: 100vh; width: 100vw; position: fixed; z-index: -1; /* Optional */ } .content { position: absolute; margin-top: 5rem; left: 50%; transform: translateX(-50%); width: 80%; }
This works similarly for background images:
.img { background: url('../assets/test_pic.jpg'); background-position: center; background-repeat: no-repeat; background-size: cover; position: fixed; height: 100vh; width: 100vw; }
While minor scrolling might occur when the URL bar hides, the major issues are resolved.
This "hack" uses a <div> instead of an <code><img alt="The Fixed Background Attachment Hack" >
tag, which might affect semantics and accessibility. If the image is crucial for meaning, using an <img alt="The Fixed Background Attachment Hack" >
with proper alt
text is better, even if it means the hack won't work perfectly. A bottom navigation bar that auto-hides might still cause problems. In such cases, JavaScript might be necessary.
The above is the detailed content of The Fixed Background Attachment Hack. For more information, please follow other related articles on the PHP Chinese website!