I am trying to incorporate a Bootstrap 4 navbar into a div with a background image. My goal is for the navbar to become sticky at the top, resize, and change color as the user scrolls down the page. However, I've noticed that when I place the navbar within the background image div, it only remains sticky until the background image scrolls out of view. It works as intended when the navbar is placed above the div containing the background image.
For those interested, you can experiment with the code by following this link:
Thank you in advance!
Edit: Here is the code: HTML:
<div class="top flex-center position-ref">
<div class="top-right links">
<a href="#">Contact</a>
<a href="#">Login</a>
</div>
</div>
<div class="container-fluid">
<span class="position-absolute trigger"></span>
<nav class="navbar navbar-expand-lg navbar-light sticky-top">
<a class="navbar-brand" href="#">Brand</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="#">Link1</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link2</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link3</a>
</li>
</ul>
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="#">Link4</a>
</li>
</ul>
</div>
</nav>
<div class="bgimg">
<div class="flex-center content full-height">
<div class="title">
Lorem ipsum dolor sit amet
</div>
</div>
</div>
<div class="row">
<div class="col">
<p>Lorem ipsum dolor sit amet,...</p>
</div>
</div>
</div>
Javascript:
(new IntersectionObserver(function(e,o){
if (e[0].intersectionRatio > 0){
document.documentElement.removeAttribute('class');
} else {
document.documentElement.setAttribute('class','stuck');
}
})).observe(document.querySelector('.trigger'));
CSS:
.flex-center {
align-items: center;
display: flex;
justify-content: center;
}
.position-ref {
position: relative;
}
.top {
background-color: #fff;
height: 60px;
}
.sticky-top {
transition: all 0.25s ease-in;
}
.stuck .sticky-top {
background-color: #326f8d !important;
padding-top: 3px !important;
padding-bottom: 3px !important;
margin-left: -1vw;
margin-right: -1vw;
}
.bgimg {
text-align: center;
background-image: url(https://placeimg.com/1000/480/animals);
background-attachment: fixed;
background-repeat-x: no-repeat;
background-repeat-y: no-repeat;
background-size: cover;
margin-left: -1vw;
margin-right: -1vw;
/* height: calc(100% - 60px); */
}
.top-right {
position: absolute;
right: 10px;
top: 18px;
}
.links > a {
color: #433b3b;
padding: 0 25px;
font-size: 12px;
font-weight: 600;
letter-spacing: .1rem;
text-decoration: none;
text-transform: uppercase;
}
.content {
height: 280px;
color: #fff;
}