修复了 nav inside scrollable div

Fixed nav inside scrollable div

我想要一个固定在可滚动 div 内的导航栏,而不是在整个 window 之上。在下面的示例中,我希望我的导航栏出现在红色区域并在我滚动时保持固定。

#containerDiv {
  padding-top: 60px;
}

#scrollDiv {
  overflow-y: scroll;
  height: 100px;
}

#scrollableContentDiv {
  background-color: red;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
<!-- JavaScript Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.bundle.min.js" integrity="sha384-b5kHyXgcpbZJO/tY9Ul7kGkf1S0CWuKcCD38l8YkeH8z8QjE0GmW1gYU5S9FOnJ0" crossorigin="anonymous"></script>

<div class="container" id="containerDiv">
  <p>Outside scrollable</p>
  <p>Outside scrollable</p>
  <p>Outside scrollable</p>
  <div id="scrollDiv" tabindex="0">
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
      <div class="container-fluid">
        <a class="navbar-brand" href="#">Navbar</a>
      </div>
    </nav>
    <div id="scrollableContentDiv">
      <p>Inside scrollable</p>
      <p>Inside scrollable</p>
      <p>Inside scrollable</p>
      <p>Inside scrollable</p>
      <p>Inside scrollable</p>
      <p>Inside scrollable</p>
    </div>
  </div>
  <p>Outside scrollable</p>
  <p>Outside scrollable</p>
  <p>Outside scrollable</p>
</div>

可以吗?

感谢您的帮助。

已修复在红色框内。使用 .sticky-top (position:sticky;)

问题是“sticky”是一个实验性的 API,不应该在生产代码中使用。但它在我测试它的 Chrome 中工作正常。此外,带有“粘性”的元素不应该是唯一的 child。它必须有兄弟(或姐妹)。

请注意,根据规范,粘性在溢出元素内不起作用:隐藏或自动。

#containerDiv {
  padding-top: 60px;
}

#scrollDiv {
  overflow-y: scroll;
  height: 100px;
}

#scrollableContentDiv {
  background-color: red;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
<!-- JavaScript Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.bundle.min.js" integrity="sha384-b5kHyXgcpbZJO/tY9Ul7kGkf1S0CWuKcCD38l8YkeH8z8QjE0GmW1gYU5S9FOnJ0" crossorigin="anonymous"></script>

<div class="container" id="containerDiv">
  <p>Outside scrollable</p>
  <p>Outside scrollable</p>
  <p>Outside scrollable</p>
  <div id="scrollDiv" tabindex="0">
    
    <div id="scrollableContentDiv">
      <nav class="navbar navbar-expand-lg navbar-dark bg-dark sticky-top">
       <div class="container-fluid">
         <a class="navbar-brand" href="#">Navbar</a>
       </div>
      </nav>
      <p>Inside scrollable</p>
      <p>Inside scrollable</p>
      <p>Inside scrollable</p>
      <p>Inside scrollable</p>
      <p>Inside scrollable</p>
      <p>Inside scrollable</p>
    </div>
  </div>
  <p>Outside scrollable</p>
  <p>Outside scrollable</p>
  <p>Outside scrollable</p>
</div>