CSS 背景颜色不粘

CSS background color not sticky

我正在尝试使从中间页面开始的导航栏在滚动时保持在屏幕顶部。我在导航栏项目上取得了成功,但是 .navbar 背景(灰色)与页面的其余部分一起滚动,并被导航栏下方容器中的背景图像所取代。感谢您对代码的任何帮助。

CSS:

.navbar_container {
    position: sticky;
    top: 0;
    display: flex;
    margin: 0px;
    padding-top: 1px;
    padding-bottom: 1px;
    background-color: gray; 
}

.navbar_item {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 5px;
}

.image_container_bg {
    display: flex;
    margin: 0px;
    background-position: center center;
    background-repeat: no-repeat;
    background-size: cover;
    background-attachment: fixed;
    opacity: 0.5;
}

HTML(目标替换为占位符):

<div class="navbar_container">
    <a class="navbar_item" href="link">
        Home
    </a>
    <a class="navbar_item" href="link">
        About
    </a>
    <a class="navbar_item" href="link">
        Help
    </a>
</div>

<figure class="image_container_bg">
    <img src="filename">
</figure>

尝试固定位置,像这样:

.navbar_container{
  top:0;
  position: sticky;
  display:flex;
  justify-content:center;
  background-color:red;
  width:100%;
}
.navbar_item{
  padding-left:3rem;
}
.wrapper{ 
height:1000px
}
<div class="wrapper">
<div class="navbar_container">
    <a class="navbar_item" href="link">
        Home
    </a>
    <a class="navbar_item" href="link">
        About
    </a>
    <a class="navbar_item" href="link">
        Help
    </a>
</div>
</div>

z-index 应用到导航栏(在这种情况下 z-index: 1 就足够了)

html, body {
  margin: 0;
  }
.navbar_container {
  position: sticky;
  top: 0;
  display: flex;
  margin: 0px;
  padding-top: 1px;
  padding-bottom: 1px;
  background-color: gray;
  z-index: 1;
}

.navbar_item {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 5px;
}

.image_container_bg {
  display: flex;
  margin: 0px;
  background-position: center center;
  background-repeat: no-repeat;
  background-size: cover;
  background-attachment: fixed;
  opacity: 0.5;
}
<div class="navbar_container">
  <a class="navbar_item" href="link">
        Home
    </a>
  <a class="navbar_item" href="link">
        About
    </a>
  <a class="navbar_item" href="link">
        Help
    </a>
</div>

<figure class="image_container_bg">
  <img src="https://placehold.it/800x1200/fba">
</figure>