Qubyte Codes

Progressive enhancement #1

Published

When I first put together the CSS for this blog I avoided a fixed header since the header felt a bit large, and I didn't want to take up too much space which could be used for content.

The solution is a header which shrinks as the reader scrolls down. This gives back a little space, and maintains access to the navigation bar (which is a part of the header). To make it look nice, the title animates between the smaller and larger states using a CSS transition. The CSS looks something like:

h1 {
  font-size: 2rem;
  margin: 1rem 0;
  transition: all 0.3s;
}

.smaller h1 {
  font-size: 1rem;
  margin: 0.5rem 0;
}

I'm a novice when it comes to CSS, so let me know if I'm missing a trick!

The markup for the top header (which has not changed), looks like:

<header class="top-header">
  <h1>...</h1>
  <nav>...</nav>
</header>

To trigger the transition, a little JavaScript is needed to detect when a scroll event occurs. When the page is not scrolled down the header has no additional classes added. When the page is scrolled a class is added to make the header h1 text and margin smaller. When the page is scrolled down and then back to the top, the header h1 text returns to its original size.

var $header = document.querySelector('.top-header');

function checkHeaderSmallText() {
  if (window.pageYOffset > 0) {
    $header.classList.add('smaller');
  } else {
    $header.classList.remove('smaller');
  }
}

window.addEventListener('scroll', checkHeaderSmallText, false);

checkHeaderSmallText();

So why is this progressive? Most importantly, no markup (with the exception of an added script tag in the head) has been added. Browsers with JavaScript disabled or screen readers will interpret the site as they did before. If the feature fails for any reason, or example if deferred scripts or classList are not supported, then an error will be thrown and the header will fail to shrink. Should CSS transitions not be supported, the header will immediately go from the larger to the smaller state on scrolling. These failure modes are acceptable in my opinion.

In the future I have a more elaborate header animation in mind. If you're interested in such things, watch this space!