Search code examples
htmlcssmobilebackground-image

CSS background-image inexplicably zooming in on mobile


Sorry if this has been answered elsewhere; the only other place I could find this issue mentioned is here but the answer given there doesn't seem relevant to my site, but I'm happy to be proven wrong.

I'm working on a site in Next.js (although I don't think the framework is relevant because this project used to be create-react-app and the same issue occurred) and our site background is a fixed starry-sky image. I'm applying that across the site by doing this in my global app.scss filesheet:

html {
    background-image: url(../public/images/background.jpg);
    background-size: cover;
    background-attachment: fixed;
    background-position: center;
    background-repeat: no-repeat;
    background-color: black;
}

This works perfectly on my desktop browser – on all viewport sizes. The first screenshot is how the site looks when using Chrome's devtools to simulate a mobile display, after reloading the site from scratch with that viewport and everything. The second screenshot is when opening the site from an actual mobile device (an iPhone XS on the Chrome mobile browser). You can see that the background image is super zoomed-in:

enter image description here enter image description here

I don't know how I could inspect the styles being applied on my phone browser, so it's hard to figure out the cause of this. Anybody have any ideas?


Solution

  • Somehow I had missed this question, which says that background-attachment: fixed is unsuppored on mobile browsers. So I gave up applying the image as a background to the html element and instead added a <div id="background" /> with this styling:

    #background {
        z-index: -1;
        background-image: url(../public/images/background.jpg);
        height: 100vh;
        width: 100vw;
        position: fixed;
        background-size: cover;
        background-position: center;
    }
    

    That fixed the issue.