html - 容器中心固定背景

标签 html css background fixed

我想创建一个具有固定背景的页眉。所以我定义了以下属性:

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

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

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

最佳答案

您可以依赖 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>

使用覆盖

.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 (组合像素值和百分比值部分)

关于html - 容器中心固定背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58277733/

相关文章:

javascript - 我必须有 content.beginPath() 和 content.closePath() 吗?

带有切换功能的 jquery 帮助

android - 为所有屏幕尺寸设置背景图像

php file_get_contents() 显示页面而不是 html 源代码

html - 如何使图像仅在我将鼠标悬停在其上时出现

html - 将图像放入 div 中而不剪切它

css - 两个不同颜色的独立 CSS 样式背景图像

javascript - 滚动 html 元素仅适用于 Chrome

jquery循环不同的背景

CSS背景全长但不是全宽