Fixing Background Image Problems on Mobile Devices
When creating a webpage where the background image extends to the full screen, maintains its aspect ratio, and stays fixed during scrolling, CSS code like the following might be used:
HTML { background: url(photos/2452.jpg) no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; }
However, applying this code on mobile devices, such as iPhones or iPads, can result in the background image becoming oversized and repeating if scrolled far enough.
The solution lies in creating a "before" pseudo element as part of the HTML body, as seen below:
body:before { content: ""; display: block; position: fixed; left: 0; top: 0; width: 100%; height: 100%; z-index: -10; background: url(photos/2452.jpg) no-repeat center center; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; }
It's important to ensure that the z-index value of the "before" pseudo element is set to a negative number (e.g., -10), as the default z-index for HTML's root element is 0. This negative value places the background as the lowest layer.
The above is the detailed content of How to Fix Full-Screen Background Image Issues on Mobile Devices?. For more information, please follow other related articles on the PHP Chinese website!