首页 > 解决方案 > 居中固定容器背景

问题描述

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

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

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

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

标签: htmlcssbackgroundfixed

解决方案


你可以依靠vhunit 结合一些calc(). 中心最初50vh150px从顶部开始的,因此我们需要翻译50vh - 150px. cover如果您希望图像在屏幕高度变化时不发生变化,但它可能不会像您想要的那样呈现,您也应该摆脱它。

我替换300px100px演示。

.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 percent values with background-position on a linear gradient组合像素和百分比值部分)


推荐阅读