About this snippet

Maximize screen space for your users with this smart navigation bar. The header slides out of view when scrolling down to let them focus on content, yet it reappears instantly when they scroll up.

Size
1.6 KB
Uses
HTML, CSS, JavaScript
Loads
Nothing external
Views
442
<header id="mainHeader" class="sticky-header">
  <div class="logo">Brand</div>
  <nav>
    <a href="#">Home</a>
    <a href="#">About</a>
    <a href="#">Contact</a>
  </nav>
</header>
<main class="content">
  <h1>Scroll Down</h1>
  <p>The header will disappear to give you more reading space.</p>
  <p>Scroll back up to see it return.</p>
  <!-- Spacer for scrolling -->
  <div style="height: 1500px"></div>
</main>
.sticky-header {
  font-family: system-ui, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  background: #ffffff;
  padding: 15px 30px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
  transition: transform 0.3s ease;
  z-index: 1000;
  box-sizing: border-box;
}
.sticky-header.hide {
  transform: translateY(-100%);
}
.logo {
  font-weight: 800;
  font-size: 1.5rem;
  color: #1f2937;
}
nav a {
  text-decoration: none;
  color: #4b5563;
  margin-left: 20px;
  font-weight: 500;
  transition: color 0.2s;
}
nav a:hover {
  color: #2563eb;
}
.content {
  padding-top: 100px;
  padding-left: 30px;
  font-family: system-ui, "Segoe UI", Roboto, sans-serif;
}
let lastScrollTop = 0;
const header = document.getElementById("mainHeader");

window.addEventListener("scroll", () => {
  const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
  
  if (scrollTop > lastScrollTop) {
    // Scroll Down
    header.classList.add("hide");
  } else {
    // Scroll Up
    header.classList.remove("hide");
  }
  
  lastScrollTop = scrollTop <= 0 ? 0 : scrollTop;
});
Esc
↑↓ moveEnter select

Start from a template

Open an .html file, or HTML, CSS, JS, Markdown, Less or TypeScript files. You can also drop them here. Styles and scripts go into their panes.

Share

Source

Keyboard shortcuts

Save