隐藏溢出的背景移动

Background moving with overflow hidden

在网站上工作时,我遇到了以下问题。 Magnific Popup(灯箱插件)将 HTML 设置为溢出:隐藏;当灯箱打开时,这可以防止滚动。

在我的页面上,我有一张固定的 header 图片:

.header {
background-image: url("http://placehold.it/1920x400");
height: 400px;
background-size: contain;
background-attachment: fixed;
}

当我打开灯箱时,html 设置为溢出:隐藏; 背景图片移动。溢出:隐藏;导致背景移动。

我不知道是什么原因导致了这种行为,我尝试了以下方法:

我简化了我的代码并最终得到了这个 Codepen,要查看移动的背景,请单击按钮。

Codepen: Link to codepen

希望你能帮到我,

沃特

编辑:

我想在不将溢出设置为自动的情况下解决移动背景。我不喜欢当灯箱打开时滚动条可见。

来自 background-attachment 的 MDN 文章:

fixed: This keyword means that the background is fixed with regard to the viewport.

因为您的元素是相对于 "viewport" 定位的,当您切换到 overflow: hidden 时,视口会随着滚动条的移除而稍微变宽,导致背景重新定位,原因是您对 background-size: contain 的使用。背景现在有更多 space 覆盖,因此尺寸略有增加。

尽管我讨厌使用 !important,但您可以覆盖插件的更改:

html{
    margin-right: 0 !important;
    overflow: auto !important;
}

如果插件使用 class 而不是直接改变 html 元素的样式,您可以覆盖它而不重要。

已找到解决此问题的方法,已在 css reddit 中发布:

  1. background-size: calc(100% - 17px) 这是第一个解决方案Codepen of first solution
  2. background-size: 100vw 这是第二个解决方案Codepen of second solution