Search code examples
htmlcssiossafaribackground-image

Setting overflow: hidden on <body> results in 1px white padding on iOS Safari


I have a background image for a webpage that is too big, and in general, I want to prevent scrolling on the webpage. The HTML looks like this

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>Test</title>
        <link href="style.css" rel="stylesheet" />
    </head>
    <body>
        <div id="header">
            Test
        </div>
    </body>
</html>

and the CSS looks like

html, body {
    height: 100%;
    margin: 0;
    padding: 0;
    width: 100%;
    overflow: hidden;
}

body {
    background-image: url("bg.jpeg");
    background-size: cover;
    background-clip: padding-box;
    display: table;
}

This code mostly achieves the desired effect (background image looks good and scrolling is prevented); however, in iOS Safari, the overflow: hidden; (which prevents scrollbars/scrolling) seems to introduce ~1px of white space around the right and bottom of the display area. I can get rid of the margin by doing something like padding: 1px instead of padding: 0, but then the scrollbars come back. Any ideas on how to get rid of this small whitespace while still preventing scrolling?

I tried adding a wrapper <div> for all the <body> content and setting the background and overflow properties on the <div>, but still didn't have luck (either got scrollbars or the odd small margins on bottom and right).


Solution

  • While I am not entirely clear why you get that white band(s) a slightly hacky workaround would be to put the background onto a before pseudo element which you make just slightly larger than the body.

    html,
    body {
      height: 100%;
      margin: 0;
      padding: 0;
      width: 100%;
      overflow: hidden;
    }
    
    body::before {
      content: '';
      position: absolute;
      left: 0;
      top: 0;
      width: calc(100% + 1px);
      height: calc(100% + 1px);
      background-image: url(https://picsum.photos/id/1015/1024/1024);
      background-size: cover;
      background-position: center center;
      background-clip: padding-box;
    }
    
    body {
      display: table;
    }
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8" />
      <title>Test</title>
      <link href="style.css" rel="stylesheet" />
    </head>
    
    <body>
      <div id="header">
        Test
      </div>
    </body>
    
    </html>