使容器背景图片居中固定

3
我想创建一个带有固定背景的页眉。因此,我定义了以下属性:
header {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 300px;
    display: block;
    background-image: url('...');
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center;
    background-attachment: fixed;
}

现在我有一个问题,背景图是根据屏幕的宽度和高度居中的。由于标头在顶部,所以标头的实际背景只是图像的顶部。此外,每次更改屏幕高度时,标头图像部分都会发生变化,这不是我的目标。
我希望图像在标头内居中(图像的中心位于标头的中心,但只有在我没有滚动时)。此外,标头图像部分应仅在更改标头宽度、高度或屏幕宽度时更改,而不是更改屏幕高度时更改。
2个回答

1
你可以依赖于vh单位和一些calc()。中心初始值为50vh,你想让它距离顶部150px,因此我们需要50vh - 150px的平移。如果你不希望图片随着屏幕高度变化而改变,你还应该去掉cover,但它可能无法呈现你想要的效果。

我已经在演示中用100px替换了300px

.header {
  height:100px;
  border:1px solid;
  background:
    url(https://picsum.photos/id/1014/1200/800) 50% calc(50% - (50vh - 50px)) fixed;
}
.not-fixed {
  background-attachment:initial;
  background-position:center;
  margin-top:20px;
}

body {
  min-height:200vh;
  margin:0;
}
<div class="header">

</div>
<div class="header not-fixed">

</div>

通过使用cover

.header {
  height:100px;
  border:1px solid;
  background:
    url(https://picsum.photos/id/1014/1200/800) 50% calc(50% - (50vh - 50px))/cover fixed;
}
.not-fixed {
  background-attachment:initial;
  background-position:center;
  margin-top:20px;
}

body {
  min-height:200vh;
  margin:0;
}
<div class="header">

</div>
<div class="header not-fixed">

</div>

你可以清楚地看到第一张图片的居中位置与第二张图片完全相同,没有使用fixed
要了解更多有关计算的详细信息,请查看此链接:在线性渐变上使用百分比值进行背景定位将像素和百分比值组合部分)。

谢谢,现在看起来好多了。但还有一个问题。图片的大小为1000x666像素。但我不希望在更改屏幕高度时看到视口发生变化。 - Kaskorian
@Matze,唯一的方法是不使用封面。有了封面就不可能了。请检查更新,我已经删除了封面。 - Temani Afif
好的,明白了。谢谢。 - Kaskorian

0
尝试将 img(在 header div 外部)和 header div 包装起来,并使用相对/绝对定位来将 header 重叠在图像之上。
完成后,您可以使用 z-index 将图像推向后面。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接