Home > front end >  Navbar scroll effect not working when having background color
Navbar scroll effect not working when having background color

Time:07-11

I have a navbar having a gradient type background(slightly black, to transparent). enter image description here

I wanted the navbar to turn completely black when scrolling, and I wrote the necessary JavaScript code, but the color changes only when I remove that background color gradient from the CSS, otherwise, it doesn't work. Is there a solution for this?

HTML Code:

<section id="header" >
<a href="#"><img src="images/logo.png" ></a>
<div>
  <ul id="navbar">
    <li><a  href="why.html">Why Snap Smile</a></li>
    <li><a href="solutions.html">Solutions</a></li>
    <li><a href="pricing.html">Pricing</a></li>
    <li><a href="about.html">About</a></li>
    <li><a href="gallery.html">Gallery</a></li>
    <li><a href=""><i ></i></a></li>
  </ul>
</div>

CSS code:

  body {
  font-family: 'Montserrat', sans-serif;
  width: 100%;
  margin: 0;
  background-color: #121212;
}

/* Header Section */
#header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 80px;
  background: rgb(0,0,0);
background: linear-gradient(180deg, rgba(0,0,0,0.6629026610644257) 0%, rgba(9,9,121,0) 57%);
  z-index: 999;
  position: sticky;
  top: 0;
  left: 0;
}

.headerr__black{
  background-color: #121212;
}

#navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

#navbar li {
  list-style: none;
  padding: 0 20px;
  position: relative;
}

#navbar li a {
  text-decoration: none;
  font-size: 1rem;
  font-weight: 600;
  color: #ffffff;
  transition: 200ms ease-in-out;
}

#navbar li a:hover,
#navbar li a.active {
  color: #e50914;
}

#navbar li a.active::after,
#navbar li a:hover::after {
  content: "";
  width: 30%;
  height: 3px;
  background: #e50914;
  position: absolute;
  bottom: -6px;
  left: 20px;
}

.logo {
  width: 10rem;
}

JavaScript Code:

const nav=document.getElementById('header');
window.addEventListener('scroll',function(){
  if(window.scrollY >= 100){
    nav.classList.add('headerr__black');
  }
  else{
    nav.classList.remove('headerr__black');
  }
});

CodePudding user response:

I think this may happen because #header selector (id selector) has a higher priority than .header__black (class selector).

Can you try to update your style, so the .headerr__black styles have higher priority ? For example:

/*
 * Now the selector specificity is {id}   {class},
 * Which is higher than just {id} for #header
 */
#header.headerr__black {
  background-color: #121212;
}

Doc - https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity

  • Related