粘性定位不适用于导航栏的柔性显示? [重复]

问题描述 投票:0回答:1

我正在尝试使用 CSS

position: sticky
属性创建一个粘性导航栏。但是,当导航栏具有柔性显示时,它似乎无法按预期工作(
display: flex
)。这是我的 HTML 和 CSS:

.container {
  margin: 0 auto;
  max-width: 80vw;
}

.container nav {
  position: sticky;
  top: 10px;
  display: flex;
  justify-content: space-between;
  box-sizing: border-box;
  padding: 20px;
  margin: 10px;
  align-items: center;
}
<div class="container">
  <nav>
    <h1>NFTHub</h1>
    <ul>
      <li>Home</li>
      <li>About Us</li>
      <li>Collection</li>
      <li>Contact Us</li>
    </ul>
    <div class="nav-btn">
      <button>Sign In</button>
      <button>Sign Up</button>
    </div>
  </nav>
</div>

我希望导航栏在滚动时粘在视口的顶部,但它不起作用。如何在保持其弹性布局的同时使导航栏具有粘性?

html css flexbox css-position
1个回答
0
投票

使整个 .container sticky

* { margin: 0; box-sizing: border-box; }

body {
  min-height: 300dvh; /* DEMO ONLY SCROLLBARS */
}

.container {
  margin: 0 auto;
  max-width: 80vw;
}

.top {
  position: sticky;
  top: 10px;
}

.container nav {
  position: sticky;
  top: 10px;
  display: flex;
  justify-content: space-between;
  box-sizing: border-box;
  padding: 20px;
  margin: 10px;
  align-items: center;
}
<div class="top container">
  <nav>
    <h1>NFTHub</h1>
    <ul>
      <li>Home</li>
      <li>About Us</li>
      <li>Collection</li>
      <li>Contact Us</li>
    </ul>
    <div class="nav-btn">
      <button>Sign In</button>
      <button>Sign Up</button>
    </div>
  </nav>
</div>

© www.soinside.com 2019 - 2024. All rights reserved.