Solved by CSS Scroll State Queries: hide a header when scrolling down, show it again when scrolling up.

Recording of the demo, recorded in Chrome Canary.

There’s a new type of CSS scroll-state query coming: scrolled

~

Unlike the scrollable scroll-state queries, scrolled remembers the last direction you scrolled into, which you can use to build “hidey bars”: when scrolling down (or having scrolled down), the hidey bar hides itself. When then scrolling back up, the hidey bar reveals itself.

Here’s the code that is needed to hide a fixed header when scrolling down:

html {
  container-type: scroll-state;
}

header {
  transition: translate 0.25s;
  translate: 0 0;

  /* Slide header up when last having scrolled towards the bottom */
  @container scroll-state(scrolled: bottom) {
    translate: 0 -100%;
  }
}

Good suggestion by meduz on Mastodon, in case the header contains some interactive content that you can focus:

Use header:not(:focus-within) to avoid hiding the bar if there’s focus in it.

~

Below is a live demo using the code above. You can try it out yourself in Chrome Canary with the experimental Web Platform Features Flag enabled. If you browser does not support scrolled scroll-state queries, the header will remain fixed in place – a nice progressive enhancement if you’d ask me 🙂

See the Pen
Hidey Bar Demo (Hide on Scroll Down, Show on Scroll Up // Scroll State Queries)
by Bramus (@bramus)
on CodePen.

The feature is expected to ship to Chrome Stable in Chrome 144.

~

If that demo looks familiar: I featured it here on bram.us before, as a demo to use scroll-driven animations to track and remember the scroll direction. Thanks to scrolled scroll-state queries, that hack is no longer needed 🙂

~

🔥 Like what you see? Want to stay in the loop? Here's how:

I can also be found on 𝕏 Twitter and 🐘 Mastodon but only post there sporadically.

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Unless noted otherwise, the contents of this post are licensed under the Creative Commons Attribution 4.0 License and code samples are licensed under the MIT License

Join the Conversation

1 Comment

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.