我的网页上的位置粘性不起作用

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

我打算让我的导航栏粘在 ul 标签上,但没有任何变化。

position: sticky
属性在我的网站上不起作用。

header ul {
  display: flex;
  justify-content: center;
  background-color: black;
  position: sticky;
  top: 0;
}
<header>
  <h1>HTML Web Page</h1>
  <ul>
    <li>Home</li>
    <li>About</li>
    <li>Editor</li>
    <li>Events</li>
    <li>Gear</li>
    <li>Reach Us</li>
  </ul>
</header>
<section>
  <div>
    <h2>This is First Heading</h2>
    <p>Some Long Paragraphs for making this page scrollable</p>
  </div>
  <div>
    <h2>This is Second Heading</h2>
    <p>Some Long Paragraphs for making this page scrollable</p>
  </div>
  <div>
    <h2>This is Third Heading</h2>
    <p>Some Long Paragraphs for making this page scrollable</p>
  </div>
  <div>
    <h2>This is Fourth Heading</h2>
    <p>Some Long Paragraphs for making this page scrollable</p>
  </div>
  <div>
    <h2>This is Fifth Heading</h2>
    <p>Some Long Paragraphs for making this page scrollable</p>
  </div>
  <div>
    <h2>This is Sixth Heading</h2>
    <p>Some Long Paragraphs for making this page scrollable</p>
  </div>
</section>

html css frontend css-position positioning
1个回答
1
投票

position: sticky
不会将元素移出流。这意味着,粘性元素仍然是父元素的子元素。一旦父元素离开视口,粘性子元素也会离开视口。

只需将标题移出标题并在标题元素上应用

position: sticky

header {
  position: sticky;
  top: 0;
}

header ul {
  display: flex;
  justify-content: center;
  background-color: black;
}
<h1>HTML Web Page</h1>
<header>
  <ul>
    <li>Home</li>
    <li>About</li>
    <li>Editor</li>
    <li>Events</li>
    <li>Gear</li>
    <li>Reach Us</li>
  </ul>
</header>
<section>
  <div>
    <h2>This is First Heading</h2>
    <p>Some Long Paragraphs for making this page scrollable</p>
  </div>
  <div>
    <h2>This is Second Heading</h2>
    <p>Some Long Paragraphs for making this page scrollable</p>
  </div>
  <div>
    <h2>This is Third Heading</h2>
    <p>Some Long Paragraphs for making this page scrollable</p>
  </div>
  <div>
    <h2>This is Fourth Heading</h2>
    <p>Some Long Paragraphs for making this page scrollable</p>
  </div>
  <div>
    <h2>This is Fifth Heading</h2>
    <p>Some Long Paragraphs for making this page scrollable</p>
  </div>
  <div>
    <h2>This is Sixth Heading</h2>
    <p>Some Long Paragraphs for making this page scrollable</p>
  </div>
</section>

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