Fixed page backgrounds on mobile (background-attachment vs position fixed)
cssmobileperformanceiosandroidcompositing
Never use background-attachment: fixed for a full-page image. Use a position: fixed pseudo-element instead. The two look identical on a desktop and behave completely differently on phones.
Why
- iOS Safari ignores
background-attachment: fixedentirely. - Android Chrome honors it by re-rasterizing every layer of that background on each scroll frame. With a multi-layer background and a full-viewport image that is a full repaint per frame; content above it flickers and drops out ("flashes a little bit but mostly doesn't show at all").
- A
position: fixedelement is composited once and never repainted while scrolling.
The pattern
body::before {
content: ""; position: fixed; inset: 0; z-index: -1; pointer-events: none;
background: url(...) center / cover no-repeat;
}
html { background-color: #...; } /* fallback color lives here */
body { background-color: transparent; } /* required */
Traps that follow immediately
- Paint order. A negative z-index child paints before any in-flow block background, so an opaque
bodybackground covers the layer entirely and the picture vanishes to flat color. Put the fallback color onhtmland makebodytransparent. - Per-layer longhands.
background-size,background-repeatandbackground-positiontake one value per layer. A tiled scanline gradient over acoverphoto needsbackground-size: auto, cover, coverandbackground-repeat: repeat, no-repeat, no-repeat, or the scanlines stretch into fat stripes. - Repeated cards: prefer
box-shadowtofilter: drop-shadow. Eachfilteris its own compositing layer, and over an opaque image the two look identical.
Example
The CRT theme on videos.jhampton.io looked broken on Justin's Android phone while the look.php sketch of the same design was perfect. Nothing reproduced in headless Chrome at any viewport. The bug was found by diffing the two pages rather than reproducing: the sketch used a position: fixed div, the theme used background-attachment: fixed on <body>. That was the whole difference. Diffing a working page against a broken one is often faster than reproduction.
See also
- Headless Chrome testing gotchas
- CSS theme switching without a flash (and contrast over photos)
- When headless tests and a real phone disagree