Home > front end >  How can i make my navigation bar stick to the top of my screen with css
How can i make my navigation bar stick to the top of my screen with css

Time:02-07

So i was creating a navigation bar for my website and it seems impossible to make it stick on the screen, its so confusing to me.

I followed Kevin Powell's tutorial on this but he didn't show how to make it stick to the top of the page.

Here is my HTML:

    <header>
        <div >
            <h1 >Navigation</h1>
    
            <nav>
                <ul>
                    <li><a href="#">Home</a></li>
                    <li><a href="#">About us</a></li>
                    <li><a href="#">Contact us</a></li>
                </ul>
            </nav>
        </div>
    </header>

And here is my CSS:

.container {
    width: 80%;
    margin: 0 auto;
}

header {
    background: rgb(155, 155, 155);
    border-radius: 0px 0px 25px 25px;
}

.logo {
    float: left;
    padding: 0px 0;
}

I had to shrink the css code a bit but the ul is not really important here.

CodePudding user response:

Use position: sticky and top:0.

nav { position: sticky; top: 0; }
div { height: 2000px; }
<nav>My nav</nav>
<div>some long div</div>

This doesn't work in IE 11.

CodePudding user response:

Simply just add this to your header tag CSS:

header{
  position: fixed;
  top: 0;
}

CodePudding user response:

Just added some css of your nav.

nav {
   overflow: hidden;
   position: fixed;
   top: 0;
   width: 100%;
}

See a demo where I used your code:- in codepen

Also,

.container {
  width: 100%;
  margin: 0 auto;
}

header {
  background: rgb(155, 155, 155);
  border-radius: 0px 0px 25px 25px;
  height: 700px;
}
nav {
  overflow: hidden;
  position: fixed;
  top: 0;
  width: 100%;
}
.logo {
  float: left;
  padding: 0px 0;
}
<header>
  <div >
    <h1 >Navigation</h1>
    <nav>
      <ul>
        <li><a href="#">Home</a></li>
        <li><a href="#">About us</a></li>
        <li><a href="#">Contact us</a></li>
      </ul>
    </nav>
  </div>
</header>

check from here;-

  •  Tags:  
  • Related