Home >Web Front-end >CSS Tutorial >How to Fix Full-Screen Background Image Repeating on Mobile Devices Without JavaScript?

How to Fix Full-Screen Background Image Repeating on Mobile Devices Without JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-12-11 04:15:09302browse

How to Fix Full-Screen Background Image Repeating on Mobile Devices Without JavaScript?

Troubleshooting Background: Fixed No Repeat Issue on Mobile Devices

Problem:

Users face difficulty in implementing a full-screen background image with a fixed position on mobile devices (iPhone and iPad). Despite the use of CSS for background styling, the image appears oversized and tends to repeat when scrolling down.

Solution:

To address this issue, a novel solution has emerged that eliminates the need for JavaScript. Introducing a new CSS snippet:

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;
}

Explanation:

  • The body:before pseudo-element creates an additional element before the body of the HTML document.
  • Absolute positioning ensures that the element remains in a fixed position relative to the viewport.
  • The negative z-index (-10) enables the element to appear behind the regular content of the page.
  • The background image, its placement, scaling, and fixing are identical to the original CSS used for desktop browsers.

It's important to note that this technique is vendor prefix-free, eliminating cross-browser compatibility issues.

The above is the detailed content of How to Fix Full-Screen Background Image Repeating on Mobile Devices Without JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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