Home > Web Front-end > CSS Tutorial > How to Fix Background Image Scaling Issues on Mobile Devices Using Only CSS?

How to Fix Background Image Scaling Issues on Mobile Devices Using Only CSS?

DDD
Release: 2024-12-13 00:15:20
Original
599 people have browsed it

How to Fix Background Image Scaling Issues on Mobile Devices Using Only CSS?

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template