Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make element hide on scroll down and appear on scroll up using JS/CSS

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading