"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why Does `background-size: cover` Fail on Mobile Safari and How to Fix It?

Why Does `background-size: cover` Fail on Mobile Safari and How to Fix It?

Published on 2024-11-18
Browse:781

Why Does `background-size: cover` Fail on Mobile Safari and How to Fix It?

Overcoming the Limitations of background-size: cover in Mobile Safari

iOS devices present a unique challenge when it comes to implementing background images that cover entire elements using background-size: cover. Despite the expected behavior, this property often yields undesirable results on these platforms.

To address this issue, a clever workaround has emerged. By adjusting the background-attachment property to scroll within a media query specifically targeting iPhones, the problematic behavior can be corrected.

Here's an updated version of the provided code:

.section {
  margin: 0 auto;
  position: relative;
  padding: 0 0 320px 0;
  width: 100%;
}

#section1,
#section2,
#section3 {
  background-size: cover;
  background-attachment: fixed;
  background-position: center center;

  @media (max-width: @iphone-screen) {
    background-attachment: scroll;
  }
}

By including this media query, the background-attachment property is set to scroll only for devices with a width less than or equal to the predefined @iphone-screen variable. This ensures that the background images behave as expected on iPhones while maintaining their fixed position on larger screens.

This solution provides a simple and elegant way to handle this common issue, allowing you to create seamless full-width background images on all devices, including iOS.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3