Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS background stretches to fill height in iOS but there is white space on scroll

this CSS gets my background to fill 100% of the screen height in iOS but there is a minor problem - when you scroll down there is initially white space, then when you release your finger and stop scrolling the background image "adjusts" and fills 100% of the screen height again. The problem does not re-occur on the same page if you continue to scroll, just the first time. Could someone please help? Thanks

#background {
  background: url(../img/background.jpg) center repeat-x;
  position: fixed;
  background-size: auto 100%;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: -1
}
like image 660
user852974 Avatar asked Dec 02 '25 08:12

user852974


1 Answers

This happens because your #background element is set to "follow" the height of the window:

#background {
    ...
    position: fixed;
    top: 0;
    bottom: 0;
    ...
}

But, the window in Safari changes its size when you scroll down the content for the first time from 460px to 529px:

enter image description here enter image description here enter image description here

As you can see from these screenshots, when the web page is loaded the window.innerHeight is equal to 460px (on iPhone5). Then, when you begin scrolling the page down while your finger touches the screen the window.innerHeight is increased to 529px but the content is not yet updated. Only when the finger is released from the screen the #background element is updated with the new window height which equals to 529px.

To fix this issue you should make sure that the #background element is higher than the initial window height by 529-460 = 69px. Or the #background element has constant height of 529px (or higher):

#background {
    ...
    position: fixed;
    top: 0;
    bottom: -69px;
    ...
}

OR

#background {
    ...
    position: fixed;
    top: 0;
    /* use height instead of bottom */
    height: 529px;
    ...
}

Here is a final code that fixes this issue:

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Fixed background</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <link rel="stylesheet" href="css/styles.css?v=1.0">
        <style>
            #background {
                background: url(bkgd.png) repeat;
                position: fixed;
                background-size: 100% auto;
                top: 0;
                left: 0;
                right: 0;
                bottom: -69px;
                z-index: -1;
            }
        </style>
    </head>
    <body>
        <div id="background"></div>
        <div style="height: 5000px;"></div>
    </body>
</html>
like image 166
smnh Avatar answered Dec 04 '25 22:12

smnh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!