Sticky honey

Creating a sticky header for mobile navigation

When building a website, often it's helpful to use a sticky header for navigation on handheld devices. A sticky header remains at the top of the viewport, even as the user scrolls down the page. Below, is my latest go-to method for implementing this.

This is what my page html page looks like.

  <header class="page-header" role="banner">

<!-- header content here -->

<div class="page-wrapper">

    <div class="page-content">
<!-- page content here -->

    <footer class="page-footer">
<!-- footer content here -->


Next, include this bit of javascript/jquery somewhere on your page.

    if ($(window).width() < 768) {      
        if ($(document).scrollTop() > 0) {
        } else {

The if statements check for two things

  • First, determine if the browsers window width is less the 768 pixels
  • If so, also determine if the browser window has been scrolled more than 0 (zero) pixels from the top.

If both of these conditions are met, the script adds the "sticky-header" class to the ".page-header" element, otherwise (else) the "sticky-header" class is removed.

This is all that's needed from javascript. Next add a bit of css to complete the task.

.page-header {
  background-color:rgba(255, 255, 255, .2);
  transition: 0.2s; /* optional transition effect */
  border-bottom:1px solid #CCC;
  height: 10em;
  margin:0 auto;
  position: relative;
.page-header.sticky-header {
  background-color:rgba(255, 255, 255, .95);
  /* position the sticky header at the top */  
  position: fixed;
  width: 100%;
  z-index:2; /* ensure the header is positioned above the page-wrapper when scrolling *

Add new comment

comment editor

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type='1 A I'> <li> <dl> <dt> <dd> <h2 id='jump-*'> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.