'HTML/CSS Position sticky is not working properly

I am trying to make a div position: sticky; but it doesn't work, here's my code:

body {
  height: 1000px;
}

header {
  position: absolute;
  width: 100%;
  z-index: 100;
}

.top-navbar {
  height: 100px;
  background-color: green;
}

nav {
  position: -webkit-sticky !important;
  position: sticky;
  top: 0;
  align-self: flex-start;
  background-color: orange;
}
<header>
  <div class="top-navbar">
    <h2>top navbar</h2>
  </div>
  <nav>
    <h1>My navbar</h1>
  </nav>
</header>


Solution 1:[1]

it seems you only want to keep the nav visible on scroll. In this case do it like below. Move sticky to header and consider a negative value for top equal to the height of top-navbar

body {
  height: 1000px;
}

header {
  position: sticky;
  top: -100px;
}

.top-navbar {
  height: 100px;
  background-color: green;
}

nav {
  background-color: orange;
}


h1,h2 {
  margin:0;
}
<header>
  <div class="top-navbar">
    <h2>top navbar</h2>
  </div>
  <nav>
    <h1>My navbar</h1>
  </nav>
</header>

Solution 2:[2]

This assumes you want to make the second nav sticky.

There is a pretty good tutorial on w3schools for this: https://www.w3schools.com/howto/howto_js_navbar_sticky.asp

Applying this to your code will be like:

// When the user scrolls the page, execute myFunction
window.onscroll = function() {myFunction()};

// Get the navbar
var navbar = document.getElementById("navbar");

// Get the offset position of the navbar
var sticky = navbar.offsetTop;

// Add the sticky class to the navbar when you reach its scroll position. Remove "sticky" when you leave the scroll position
function myFunction() {
  if (window.pageYOffset >= sticky) {
    navbar.classList.add("sticky")
  } else {
    navbar.classList.remove("sticky");
  }
}
body {
  height: 1000px;
}

header {
  position: absolute;
  width: 100%;
  z-index: 100;
}

.top-navbar {
  height: 100px;
  background-color: green;
}

nav {
  position: -webkit-sticky !important;
  position: sticky;
  top: 0;
  align-self: flex-start;
  background-color: orange;
}
  
.sticky {
  position: fixed;
  top: 0;
  width: 100%;
}
<header>
  <div class="top-navbar">
    <h2>top navbar</h2>
  </div>
  <nav id="navbar">
    <h1>My navbar</h1>
  </nav>
</header>

Of course, you can do this without JavaScript, but for compatibility with older browsers, you might want to consider this option.

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Temani Afif
Solution 2