【问题标题】:How do I prevent a fixed cover background image resizing on a mobile device如何防止在移动设备上调整固定封面背景图像的大小
【发布时间】:2021-01-07 19:58:51
【问题描述】:

我想在网站的标题中使用全屏、固定、响应式背景图片。我有一些在桌面浏览器上运行良好的 css,但在 android 上的 chrome 上,当浏览器地址栏显示/隐藏时,滚动浏览网站会导致图像移动/调整大小。

目前我使用 100vh 作为标题的高度,background-attachment: fixedbackground-size: cover。根据我在以下链接中阅读的内容,100vh 的大小应始终像地址栏被隐藏一样。 https://developers.google.com/web/updates/2016/12/url-bar-resizing

我还尝试使用 javascript 来获取初始视口高度,并将标题高度设置为此值。它似乎也不起作用。

这是一个非常简单的示例,我也将其上传到S3 bucket 以便在移动设备上查看:

<html>
  <head>
    <style>
      html,
      body {
        margin: 0;
      }

      .background {
        background-image: url(./image.jpg);
        background-attachment: fixed;
        background-repeat: no-repeat;
        background-size: cover;
        height: 100vh;
      }
    </style>
  </head>
  <body>
    <header class="background"></header>
    <h1>Should not resize on mobile scroll</h1>
  </body>
</html>

【问题讨论】:

  • 您可以使用background-size: 100%; 调整所有设备中的背景图像的大小

标签: html css


【解决方案1】:

给你的.background元素一个绝对位置,并给&lt;h1&gt;添加一个边距:

<html>

<head>
    <style>
        html,
        body {
            margin: 0;
        }

        .background {
            background-image: url(./image.jpg);
            background-attachment: fixed;
            background-repeat: no-repeat;
            background-size: cover;
            height: 100vh;
            position: absolute;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
        }

        h1 {
            margin-top: 100vh;
        }
    </style>
</head>

<body>
    <header class="background"></header>
    <h1>Should not resize on mobile scroll</h1>
</body>

</html>

【讨论】:

  • 这仍然会在 android chrome 上滚动时触发图像的大小调整
  • 有趣。我会看看我能不能解决这个问题。
猜你喜欢
  • 2013-03-27
  • 2023-01-30
  • 2014-06-11
  • 2017-11-27
  • 1970-01-01
  • 2016-02-15
  • 2017-10-25
  • 2012-05-05
  • 1970-01-01
相关资源
最近更新 更多