htmlcssfrontendcss-positionpositioning

The Position Sticky is no Working on my Web page


I'm going to make my navbar sticky targeting the ul tag but nothing changes. the position: sticky property is not working on my web.

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>


Solution

  • position: sticky will not move an element out of the flow. That means, that the element that is sticky, remains a child element of the parent element. As soon as the parent element leaves the viewport, so will the sticky child element.

    Simply move the title headline out of the header and apply position: sticky on the header element:

    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: instead of the header, a nav element would be more appropriate. You can even include the nav inside the header as an additional container.