容器的中心固定背景

问题描述 投票:1回答:2

我想创建一个具有固定背景的标题。因此,我定义了以下属性:

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;
}

现在我有以下问题。当前,背景根据屏幕的宽度和高度居中。由于标题位于顶部,因此标题的实际背景就是图像的顶部。此外,每当我更改屏幕高度时,标题图像部分都会更改,这不是我的目标。

我希望图像在标头中居中(图像的中心在标头的中心,但前提是我没有向下滚动)。此外,仅当我更改标题宽度,高度或屏幕宽度时,标题图像部分才应更改,但如果更改了屏幕高度,则标题图像部分应该不会更改。

html css background fixed
2个回答
0
投票

尝试将img(在标题div外部)和标题div换行,并使用相对/绝对位置将标题叠加在图像顶部。

完成此操作后,您可以使用z-index向后推动图像


-1
投票

您可以将vh单元与某些calc()结合使用。中心最初是50vh,而您希望它从顶部开始是150px,因此我们需要翻译50vh - 150px。如果您希望图像在屏幕高度变化时不发生变化,但可能无法如您所愿地呈现,则也应该摆脱cover

我在演示中将300px替换为100px

.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

要获取有关计算的更多详细信息,请检查以下内容:Using percentage values with background-position on a linear gradient像素和百分比值的组合]部分]] >>

© www.soinside.com 2019 - 2024. All rights reserved.