【问题标题】:Center fixed background of container居中固定容器背景
【发布时间】:2019-10-07 22:05:39
【问题描述】:

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

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


    【解决方案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组合像素值和百分比值部分)

    【讨论】:

    • 谢谢,现在看起来好多了。但是一个问题仍然存在。图像的大小为 1000x666 像素。但是当我改变屏幕高度时,我不想看到视口改变。
    • @Matze 唯一的方法是不使用封面。有掩护是不可能的。检查我删除封面的更新
    • 好的,知道了。谢谢。
    【解决方案2】:

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

    完成后,您可以使用 z-index 将图像向后推

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-30
      • 1970-01-01
      • 1970-01-01
      • 2018-05-17
      • 1970-01-01
      • 2020-11-05
      相关资源
      最近更新 更多