这是我的代码:
background-color:#fff;
background-attachment:fixed;
background-repeat:no-repeat;
background-size:cover;
-moz-background-size: cover;
-webkit-background-size: cover;
-o-background-size: cover;
background-position: center center;
它适用于桌面、iPad 和 Android 移动设备:
在 iPhone 上的 Chrome 和 Safari 上,背景太大:
这种情况会发生,尤其是在 iOS 上,当您有
background-attachment:fixed
时。在移动设备上,我通常将 background-attachment:scroll
放在 @media
查询中。
正如 @RyanKimber 指出的那样,固定附加图像使用整个
<body>
尺寸。在移动设备上,它会变得非常高,从而使您的图像变得模糊。将附件设置回 scroll
可以让您的封面图像在其自己的容器内拉伸。
详细阐述 Ryan 的答案,无需添加任何新的
html
节点或使用 @media
查询,仅使用一个 css。
如果您想在包括 iOS 在内的所有设备上保留
大小的cover
背景,而不添加新节点,那么技巧就是对元素(主体) 本身而不是背景进行 固定定位,因为固定的背景和封面尺寸会扰乱 iOS。fixed
它在生产中也像 iOS 上的魅力一样工作:https://www.doklist.com/
此代码不起作用,因为 iOS 使用
document
的高度而不是 viewport
:
body {
background: url(https://www.w3schools.com/css/trolltunga.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
现在这就是魔法,
body:after
被固定,并且不是背景:
body:after{
content:"";
position:fixed; /* stretch a fixed position to the whole screen */
top:0;
height:100vh; /* fix for mobile browser address bar appearing disappearing */
left:0;
right:0;
z-index:-1; /* needed to keep in the background */
background: url(https://www.w3schools.com/css/trolltunga.jpg) center center;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
我可以使用 body 本身,“position:fixed;overflow-y:scroll”,但我不想弄乱主体的定位和我的整体布局。
因此,在 body:after 上执行此操作是一个非常简单的修复。我已经在 Mac 和 iOS 上使用 firefox、safari、chrome 测试了该解决方案。
我还为此创建了一个 github 存储库,其中包含 2 个示例:https://github.com/thesved/fixed-cover-background
这里有一个简单的解决方法,让Safari浏览器中的图片可以正常显示(仅在Safari浏览器中滚动,而不是在其他媒体中固定)
@supports ( -webkit-touch-callout : none) {
.selector {
background-attachment:scroll
}
}
@supports not ( -webkit-touch-callout : none) {
.selector {
background-attachment: fixed;
}
}
这也给我带来了很多问题。问题是 iOS 使用 body 的完整高度和宽度而不是视口来决定大小。
我们的解决方案是创建一个新的
<div class="backdrop"></div>
。
我们将背景应用到这个
div
并给它position: absolute; top: 0; bottom: 0; left: 0; right: 0
。
由于这个 div 现在是视口的大小,所以
background-size: cover
工作得很好。
将背景附件从固定更改为滚动。
.yourClass {
background-attachment: scroll;
}
.imageDiv {
background: url('image.jpg') center center no-repeat fixed;
background-size: cover;
}
@supports (-webkit-touch-callout: none) {
.imageDiv {
background: url('image.jpg') center top no-repeat scroll;
background-size: auto 100vh;
}
}
这篇文章回答了您的问题:为什么 CSS background-size: cover 在 iOS 上的纵向模式下不起作用?
并非所有浏览器都能识别背景大小的 cover 关键字,因此,只需忽略它即可。
因此,我们可以通过将背景大小设置为 100% 宽度或高度(具体取决于方向)来克服该限制。我们可以定位当前方向(以及 iOS 设备,使用设备宽度)。有了这两点,我认为你可以在 iOS 上以纵向模式使用 CSS background-size:cover
请参阅该帖子以获取更多资源。
你也可以尝试一下
background-size: contain;
如果它对你和对我一样有效, 谢谢。
试试这个:
background: url( /gfx/background.jpg ) no-repeat top center fixed;
background-size: 100vmax 100vmax;
如前所述,“覆盖”将覆盖文档高度,而不是视图高度。大多数单位不会按预期工作,因此 vmax。
并不是真正的覆盖,用方形图像就可以完成工作:)