Fixed Background Image Scaling Issue on Mobile Devices
Applying the CSS styles provided in the question to an HTML element achieves the desired effect of scaling a background image to fit the entire screen, maintaining its aspect ratio, and staying fixed in place on desktop browsers. However, these styles fail to produce the same result on iPhones and iPads. On those devices, the background image extends beyond the viewport, and it starts repeating if scrolled down sufficiently.
To address this issue, an innovative solution has been developed that eliminates the need for JavaScript:
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; }
This solution creates a new element using the :before pseudo-class, which is positioned absolutely over the entire body element. The background image is assigned to this element with the desired scaling and placement properties. By setting a negative z-index value of -10, this element becomes the background for the entire page, ensuring it remains behind all other content.
This technique provides a straightforward and effective method for fixing background images on mobile devices, addressing the limitations encountered with the original CSS styles.
The above is the detailed content of How to Fix Background Image Scaling Issues on Mobile Devices Using Only CSS?. For more information, please follow other related articles on the PHP Chinese website!