【问题标题】:Background image cover behaves different on mobile Chrome背景图像封面在移动 Chrome 上的行为不同
【发布时间】:2019-03-21 02:39:35
【问题描述】:

我们试图为我们的内容设置一个覆盖整个视口的固定背景图像(就像内容漂浮在上面的墙纸一样)。这是我一直用来完成此操作的代码:

<html>
<head>
<meta name="viewport" content="width=device-width; initial-scale=1; maximum-scale=1">
</head>
<body>

<div>
</div>

<style>
div {

height: 150vh; 

background: url(https://www.google.com/logos/doodles/2019/spring-equinox-2019-northern-hemisphere-5139135894388736.3-l.png) no-repeat center fixed;
background-size: cover;

}
</style>

</body>
</html>

您也可以在这里查看:http://neonorb.com/background-test.html

在桌面 Chromium 和 Firefox 以及移动 Firefox 上,它的行为符合我的预期。也就是说,容器是 150vh,您可以在背景图像保持静止的同时滚动。

但是,如果您在移动 Chrome 中查看它,图像会占据其容器的整个高度(即 150vh)并且实际上是滚动的并且不是固定的。

这是移动 Chrome 中的错误吗?还是这种行为实际上是正确的,并且该错误实际上存在于桌面 Chromium 和两个 Firefox 中?还是我做错了什么?

编辑:

background-size:cover; 的行为进行一些研究...它说cover 仅涵盖"background positioning area"。就其本身而言,这很好。

但是,当您同时应用 background-attachment:fixed; 时,图像将被视为 position:fixed;

那么为什么看起来大多数浏览器都像这样覆盖整个视口,而移动版 Chrome 却没有呢?

【问题讨论】:

    标签: html css


    【解决方案1】:

    如果您打算将背景应用于 div,而不是 body 元素本身;确保您的 div 与视口(或您希望背景覆盖的区域)保持相同的大小:

    #div-with-background {
        display: block;
        position: fixed;
        width: 100vw;
        height: 100vh;
        left: 0;
        top: 0;
        margin: 0;
    
        background: url(https://www.google.com/logos/doodles/2019/spring-equinox-2019-northern-hemisphere-5139135894388736.3-l.png) no-repeat center fixed;
        background-size: cover;
    }
    

    您还需要删除 html 和 body 标签上的边距:

    html, body {
        margin: 0;
        padding: 0;
    }
    

    小提琴:https://jsfiddle.net/ne95d4za/

    【讨论】:

    • 要添加到这个答案,使正文具有背景图像并将 css 应用于正文
    【解决方案2】:

    您将在移动版 Safari 上看到相同的“错误”。实际上更糟糕的是,Chrome 会自动设置封面的背景大小,而 Safari 则不会。

    我认为禁用它的原因是为了避免触摸屏上的错误,固定元素有问题。

    我还没有找到不使用视差效果的解决方案,但很高兴知道如何解决该问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-21
      • 1970-01-01
      • 2018-01-19
      相关资源
      最近更新 更多