首页 > 解决方案 > 如何强制粘性导航栏“覆盖”其内容

问题描述

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

* {
  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>

正如您在滚动之前看到的那样,粘性导航栏最初位于内容段落的上方。但是,如果 navbar 类从 更改stickyfixed,那么 navbar 会覆盖内容(就像我想要的那样),但它不会随着容器滚动,因为它已被转换。

如何强制粘性导航栏将内容放在其下方,以便它始终像其后内容的覆盖一样?

如果上述情况不可行,那么如何强制固定导航栏在转换后的容器中与用户一起滚动?请注意,我想避免与此答案类似的事情(这是我目前正在使用的),因为它会导致滚动时固定容器上的抖动运动。

标签: htmlcssscrollcss-positionsticky

解决方案


使用 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>


推荐阅读