I’ve got a header component that is made up of two levels of navigation:
body {
margin: 0;
}
.header-container {
position: sticky;
top: 0;
}
.skinny-banner {
background-color: green;
height: 40px;
transition: all 0.2s linear;
color: white;
text-align: center;
}
.main-nav {
min-height: 112px;
background-color: black;
color: white;
text-align: center;
}
.dummy-content {
background-color: lightyellow;
height: 500px;
}
<div class="header-container">
<div class="skinny-banner">Skinny banner that should hide when scrolling down and appear when scrolling up</div>
<div class="main-nav">Should always be visible and should pin to top when skinny banner is hidden</div>
<div class="dummy-content"></div>
</div>
How can I ensure that the skinny banner hides when the user scrolls down, and becomes visible again when scrolling up whilst ensuring that the main-nav remains sticky to the top when the skinny banner is hidden?
I’d like to avoid using JQuery and using vanilla JS/CSS.
>Solution :
So you need to set the position: sticky and top: 0 to the .main-nav element, not the .header-container element.
body {
margin: 0;
}
.skinny-banner {
background-color: green;
height: 40px;
transition: all 0.2s linear;
color: white;
text-align: center;
}
.main-nav {
min-height: 112px;
background-color: black;
color: white;
text-align: center;
position: sticky;
top: 0;
}
.dummy-content {
background-color: lightyellow;
height: 500px;
}
<div class="header-container">
<div class="skinny-banner">Skinny banner that should hide when scrolling down and appear when scrolling up</div>
<div class="main-nav">Should always be visible and should pin to top when skinny banner is hidden</div>
<div class="dummy-content"></div>
</div>