Navbar change position

Hello everyone, Please I need assistance on my page. I want the navbar to change its position to the top when I scroll down and it should be fixed.

Hey ya,

The problem is the z-index of the element.

.sticky{
  position: fixed; 
  top:0;
  width: 100%; 
  z-index:1;
}

using your code it will automatically move to the top without scrolling but that is not exactly what I want.
I want a situation where it will retain the previous position which is under the image then when I scroll pass the image it will automatically move to the top.

I’ve made some changes that make a soft transition.

Here I’ve moved the nav to inside the hero-image, then I can have a hierarchy and I’ve given the class not-fixed to the navbar:

<div class="hero-image">
  <!-- <img src="https://images2.imgbox.com/24/1c/FsJ4AwKi_o.jpg" alt=""> -->
  <div class="portfolio">
    <h2 class="portfolio-title"><span class="portfolio-title--small">Hi there, I'm</span> Esther Itolima
      <hr>
    </h2>
    <p class="portfolio-intro">A frontend web developer with great passion for tech and fascinated <br> to solve real world problem with software.</p>
  </div>
  <nav id="navbar" class="not-fixed">
            <ul>
              <li><a href="#follow-me">Follow me</a></li>
              <li><a href="#contact-me">Contact me</a></li>
              <li><a href="#concepts">Concepts</a></li>
              <li><a href="#about-me">About Me</a></li>
            </ul>
          </nav> 
</div>

Then I’ve add those attrs to the not-fixed, this will make your nav to stay at the bottom!
And I’ve also put position: relative, with this the nav bar will only be absolute at hero-image. The last change is that I’ve set #navbar to be always 100% width.

.hero-image{
  ...
  position: relative;
}

#navbar{
  width: 100%; 
  ...
}

.not-fixed{
  position:absolute;
  bottom:0;
}

.sticky{
  position: fixed; 
  width: 100%; 
  top:0;
  z-index:1;
}

And the last one, I’ve changed sticky to be based on about-section, then I’ve removed the #navbar heigth so when it reachs the top of the about-section minus 75 px (Same as the top of the navbar) it will be fixed.

var about = document.getElementById("about-section");
var sticky = about.offsetTop - 75;


function myFunction() {
  if (window.pageYOffset >= sticky) {
    navbar.classList.add("sticky");
    navbar.classList.remove("not-fixed")
  } else {
    navbar.classList.add("not-fixed")
    navbar.classList.remove("sticky");
  }
}

I’ve forked your code, so you can see all the changes here: https://codepen.io/pedrobslisboa/pen/LJQVBE

See ya, keep coding

Hey Esther, did it work?

Give us feedback, if you have any doubt just ask.
If you understood, please mark the post as the solution to close the topic :slight_smile:

Yessss! it worked…thanks so much!

1 Like

You’re welcome :slight_smile: