'Navigation bar fixed after scroll?

I have a navigation bar after header and i want that to be stuck at top of the page while scrolling down.

can i do with position:relative?? Unlike position:fixed with the help of the following script or any other better way?

$(window).scroll(function () {
if ($(window).scrollTop() > 100) {
    $('#header').css('top', $(window).scrollTop());
}});

here is my fiddle!

black color background bar to be stuck at the top of the page

please help me out to fix that, thank you in advance.



Solution 1:[1]

you can solve it with css:

html:

    <nav id= "header">
      <ul>
        <li><a href="#"> Link 1 </a></li>
        <li><a href="#"> Link 2 </a></li>
        <li><a href="#"> Link 3 </a></li>
      </lu>
    </nav>

css:

    #header{
    position: sticky;
    top: 0; /* Position where u want it to stick, can be a
               percentage, px, vh or any position unit */
    z-index:150; /* to keep it on top layer in order not to be 
                    masked by another element*/
    }

check this link: https://elextutorial.com/learn-css/css-position-fixed-scroll-sticky/

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