如何强制粘性导航栏 "overlay" 其内容

How do I force a sticky navbar to "overlay" its content

假设我有一个如下所示的导航栏:

* {
  box-sizing: border-box;
}

html,
body {
  width: 100%;
  height: 100vh;
  margin: 0;
  padding: 0;
}

body {
  display: flex;
  justify-content: center;
}

.container {
  width: 100px;
  height: 100%;
  transform: translateX(50px);
  /* An example transform (I can't use position: fixed) */
  background-color: green;
  overflow-y: scroll;
}

.navbar {
  width: 100%;
  height: 50px;
  background-color: rgba(255, 255, 0, 0.5);
  top: 0;
}

.navbar.sticky {
  position: -webkit-sticky;
  position: sticky;
}

.navbar.fixed {
  position: fixed;
}
<div class="container">
  <div class="navbar sticky">
  </div>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
</div>

正如您在滚动之前看到的,粘性导航栏最初位于内容段落上方。但是,如果导航栏 class 从 sticky 更改为 fixed,那么导航栏会覆盖内容(如我所愿),但它不会随容器滚动,因为它是变形了。

如何强制粘性导航栏将其后的内容置于其下方,使其始终表现得像其后内容的叠加层?

如果以上不可能,那么我如何强制固定导航栏在转换后的容器中随用户滚动?请注意,我想避免类似于(这是我目前正在使用的),因为它会导致滚动时固定容器上的抖动。

用 margin-bottom 减去导航栏的高度就可以了。

* {
  box-sizing: border-box;
}

html,
body {
  width: 100%;
  height: 100vh;
  margin: 0;
  padding: 0;
}

body {
  display: flex;
  justify-content: center;
}

.container {
  width: 100px;
  height: 100%;
  transform: translateX(50px);
  /* An example transform (I can't use position: fixed) */
  background-color: green;
  overflow-y: scroll;
}

.navbar {
  --navbarheight: 50px;
  width: 100%;
  height: var(--navbarheight);;
  background-color: rgba(255, 255, 0, 0.5);
  top: 0;
}

.navbar.sticky {
  position: -webkit-sticky;
  position: sticky;
  margin-bottom: calc(0px - var(--navbarheight)); /* or -50px in other words */
}

.navbar.fixed {
  position: fixed;
}
<div class="container">
  <div class="navbar sticky">
  </div>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
  <p>Content</p>
</div>