CSS背景延伸到填充iOS的高度,但滚动上有空白

这个CSS得到我的背景填充在iOS的100%的屏幕高度,但有一个小问题 – 当你向下滚动最初是空白,然后当你松开你的手指,并停止滚动背景图像“调整”,并填充100屏幕高度的百分比再次。 如果您继续滚动,只是第一次,问题不会重新出现在同一页面上。 有人可以帮忙吗? 谢谢

#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 } 

发生这种情况是因为#background元素设置为“跟随”窗口的高度:

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

但是,当您首次将内容向下滚动到460px529px时,Safari中的window改变其大小:

在这里输入图像说明在这里输入图像说明在这里输入图像说明

从这些屏幕截图中可以看到,当网页加载时, window.innerHeight等于460px (在iPhone5上)。 然后,当您开始向下滚动页面而手指触摸屏幕时, window.innerHeight会增加到529px但内容尚未更新。 只有当手指从屏幕上释放时, #background元素才会更新,新的窗口高度等于529px

要解决这个问题,你应该确保#background元素高于初始窗口高度529-460 = 69px 。 或#background元素具有529px (或更高)的恒定高度:

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

要么

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

以下是修复此问题的最终代码:

 <!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> 

我刚刚解决了这个问题。 对我来说,问题是当我的身体标记带有背景图像,背景大小被遮盖时,空白显示。 要解决这个问题,我设置了:

background-size: 100vw 100vh;

然后设置我遇到问题的媒体查询

 {background-size: cover;} 

为什么不使用背景大小:封面。 这样背景图片将始终填充附加的div或body标签

<name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0," />

body {background-size:cover;

}

尝试在背景上使用视口单元

background-size: 100vw 100vh;

但首先添加视口元标记到您的页面:

<meta name="viewport" content="width=device-width, initial-scale=1.0" />

注意:

vw和vh单元不完全支持,请查看这里支持的浏览器。

您可以通过使用较长的转换延迟来解决此问题,以防止元素大小调整。

例如:

 transition: height 250ms 600s; /*10min delay*/ 

与此平衡的是它防止包括在设备旋转元素的大小,但是你可以使用一些JS检测orientationchange和重置高度,如果这是一个问题。

 html, body { display: block; height: 100%; width: 100%; } body { background-image: url('some/image.jpg'); background-repeat: repeat-x; background-attachment: fixed; background-position: center center; background-size: contain; } 

的jsfiddle