Home > Article > Web Front-end > Why Does background-size: cover Fail on Mobile Safari and How to Fix It?
Overcoming Mobile Safari's Limitations with CSS background-size: cover
In the realm of web development, it's often desirable to have background images that seamlessly stretch to fill the entire container. While CSS offers the property background-size: cover for this purpose, it poses an unexpected challenge when it comes to iOS devices.
The Problem
When applying background-size: cover to a div on iOS devices, the background image fails to cover the entire area. Instead, it maintains its original aspect ratio and scales down, resulting in a misalignment between the image and the container.
Solution
The issue lies not with background-size: cover but with the background-attachment: fixed property. To resolve this, a media query can be used to override the attachment behavior for iPhone devices, allowing the background image to scroll with the content.
.section { ... background-attachment: fixed; background-position: center center; } @media (max-width: @iphone-screen) { .section { background-attachment: scroll; } }
In this example, @iphone-screen is a pre-defined variable that represents the maximum screen width for iPhone devices. By setting background-attachment to scroll for these devices, the background image will now fully cover the container, adjusting to the varying viewport width and content size.
The above is the detailed content of Why Does background-size: cover Fail on Mobile Safari and How to Fix It?. For more information, please follow other related articles on the PHP Chinese website!