Position Sticky is no Working on my web page [重复]

The Position Sticky is no Working on my Web page [duplicate]

提问人:Authreborn 提问时间:9/18/2023 最后编辑:tacoshyAuthreborn 更新时间:9/18/2023 访问量:21

问:

我将使我的导航栏具有针对 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 前端 css 位置 定位

评论


答:

1赞 tacoshy 9/18/2023 #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>

PS:而不是标题,元素会更合适。您甚至可以将导航作为附加容器包含在标头中。nav