Position: sticky (top -1px)

Inspired from https://codepen.io/anon/pen/vqyQEK

by Roberto Apasajja

HTML

<div id="zirafah">I'm a header, beep boop.</div>

CSS

body {
  margin: 0;
  height: 2000px;
}

#zirafah {
  background: magenta;
  position: sticky;
  top: -1px;
}

#zirafah[stuck] {
  background: grey;
}

JavaScript

const observer = new IntersectionObserver( 
  ([e]) => e.target.toggleAttribute('stuck', e.intersectionRatio < 1),
  {threshold: [1]}
);

observer.observe(document.querySelector('#zirafah'));