Skip to content

Build a Smart Sticky Toolbar That Never Covers What People Are Reading

By 12 min read

A toolbar under your articles that steps aside when readers scroll down and comes back when they scroll up.

id
The words Build a Smart Sticky Toolbar next to an article with a small toolbar pinned at the bottom

A smart sticky toolbar is a toolbar that stays pinned to the bottom of the screen while you read, steps aside when you scroll down, and comes back as soon as you scroll up a little. In Next.js 16 you can build the whole thing with one scroll listener, one IntersectionObserver, and a few lines of CSS, no extra libraries. As of October 2026 there's also a pure CSS option through scroll-state(scrolled), but it only works in Chromium-based browsers, so JavaScript is still the main road.

You've probably seen a site where the header eats a third of your phone screen, there's a cookie banner at the bottom, and a floating chat button in the corner. What's left for the actual text is a thin slice, like watching a match from the stands while the guy in front of you stands up with a giant banner. The toolbar under every article on aconymous.com came from that same frustration. I wanted text size, share, and comments to always be close by, without getting in the way of someone who's trying to read.

In this post I'll take it apart, from the scroll direction logic to the accessibility details that usually get forgotten. All the code has been tested on Next.js 16.4.2, and there's a playground in the middle of the article you can play with right away.

What Is a Smart Sticky Toolbar?

A smart sticky toolbar is a toolbar with a fixed position on screen that knows when to show up and when to hide. What sets it apart from a regular sticky toolbar comes down to three behaviors.

First, it only appears inside the article. While the reader is still at the title, nobody needs it yet. Once they reach the comments, it has to move out of the way so it doesn't cover the submit button. Second, it reads scroll direction. Scrolling down usually means someone is reading, so the toolbar hides. Scrolling up usually means they're looking for something, so it shows up. Third, it never becomes an obstacle, not for the eyes, not for thumbs, and not for keyboards.

That third one is the one people skip most often, so it gets its own section later.

Try the Playground First

Before we get to the code, play with the simulation. Scroll inside the small screen below, then change the settings. Keep an eye on the delta value. Movements smaller than the threshold are ignored, and the toolbar only starts reacting once the scroll position passes the "start reacting after" point.

Demo

Also try turning off "Only inside the article" and scroll all the way to the comments. The toolbar will sit right on top of the comment box, and you'll see immediately why that boundary matters. Turn on "Reduce motion" and the toolbar stops running away, which is exactly what people with that setting enabled in their OS experience.

Project Structure

I started from a Next.js 16 project created with create-next-app using the default settings. These are the only files we touch:

app/
├── layout.tsx
├── globals.css
├── _components/
│   ├── scroll-direction.tsx
│   └── site-header.tsx
└── blog/
    └── [slug]/
        ├── page.tsx
        └── reader-bar.tsx

The responsibilities are split on purpose. ScrollDirection only reads the scroll direction and writes it as an attribute on the <html> element. ReaderBar only knows whether the reader is inside the article. Deciding when to show and when to hide is left to CSS. That way the header and the toolbar can react together without knowing about each other, and React doesn't have to re-render every time you scroll.

Step 1: Reading Scroll Direction Without Making the Browser Sweat

File app/_components/scroll-direction.tsx:

TypeScript
'use client'

import { useEffect } from 'react'

type Props = { threshold?: number; offset?: number }

export function ScrollDirection({ threshold = 8, offset = 120 }: Props) {
  useEffect(() => {
    const root = document.documentElement
    const calm = window.matchMedia('(prefers-reduced-motion: reduce)')
    let last = window.scrollY
    let frame = 0

    const set = (value: 'up' | 'down') => {
      if (root.dataset.scroll !== value) root.dataset.scroll = value
    }

    const read = () => {
      frame = 0
      const y = Math.max(0, window.scrollY)
      const delta = y - last
      if (calm.matches || y < offset) {
        set('up')
        last = y
        return
      }
      if (Math.abs(delta) < threshold) return
      set(delta > 0 ? 'down' : 'up')
      last = y
    }

    const onScroll = () => {
      if (!frame) frame = requestAnimationFrame(read)
    }

    const onFocus = (event: FocusEvent) => {
      if (event.target instanceof Element && event.target.closest('[data-sticky]')) set('up')
    }

    set('up')
    window.addEventListener('scroll', onScroll, { passive: true })
    document.addEventListener('focusin', onFocus)
    return () => {
      window.removeEventListener('scroll', onScroll)
      document.removeEventListener('focusin', onFocus)
      cancelAnimationFrame(frame)
      delete root.dataset.scroll
    }
  }, [threshold, offset])

  return null
}

The code is short, but a few small decisions here have a big effect.

The listener is registered with { passive: true }. That's a promise to the browser that we'll never call preventDefault(), so it can scroll the page right away without waiting for our JavaScript to finish. The full explanation is in Chrome's article on passive event listeners.

The read is deferred to requestAnimationFrame so the work lines up with the browser's rendering schedule. While a frame is still pending, further events are ignored, so our logic runs at most once per frame, whether the screen is 60 Hz or 120 Hz.

Then there's threshold.

An 8 pixel movement threshold: small scroll movements under the threshold are ignored, and the toolbar only hides or comes back once a movement passes it

Without it, a 1 pixel brush on the trackpad is enough to make the toolbar show, hide, and show again, and your reader will think their screen is haunted. Notice that last only updates when the movement crosses the threshold. So small movements added up, say 3 pixels five times, still count as one 15 pixel movement.

Math.max(0, window.scrollY) is there for Safari on iPhone. When you pull the page past the top, the bounce effect can make scrollY briefly negative, and without that guard the direction can be read backwards.

offset keeps the header and toolbar visible for the first 120 pixels. In that area people are usually still reading the title, and a header that runs off after a tiny scroll just feels rude.

People who enabled reduced motion in their OS are respected through matchMedia('(prefers-reduced-motion: reduce)'). For them, the header and toolbar never hide, because elements sliding up and down with the scroll are among the movements most likely to cause discomfort.

Finally, focusin. If a keyboard user presses Tab and focus lands inside an element with the data-sticky attribute, the direction is forced to up so that element shows up. Without this, a button can receive focus while it's hiding off screen.

Step 2: A Header That Steps Aside Too

File app/_components/site-header.tsx:

TypeScript
import Link from 'next/link'

export function SiteHeader() {
  return (
    <header className="site-header" data-sticky>
      <Link href="/" className="logo">
        Dev Notes
      </Link>
      <nav aria-label="Main">
        <Link href="/blog/toolbar-pintar">Blog</Link>
      </nav>
    </header>
  )
}

This header stays a Server Component. It doesn't need any state, because what hides it is CSS reading the data-scroll attribute on <html>. The data-sticky attribute is just a marker for the focus logic above.

Then mount both in the root layout. File app/layout.tsx:

TypeScript
import type { Metadata, Viewport } from 'next'
import { ScrollDirection } from './_components/scroll-direction'
import { SiteHeader } from './_components/site-header'
import './globals.css'

export const metadata: Metadata = {
  title: { default: 'Dev Notes', template: '%s · Dev Notes' },
}

export const viewport: Viewport = {
  viewportFit: 'cover',
}

export default function RootLayout({ children }: LayoutProps<'/'>) {
  return (
    <html lang="en">
      <body>
        <ScrollDirection />
        <SiteHeader />
        {children}
      </body>
    </html>
  )
}

viewportFit: 'cover' makes Next.js write viewport-fit=cover into the viewport meta tag. Without it, the env(safe-area-inset-bottom) value we use in CSS later stays 0 on iPhone, and the toolbar can end up hugging the home indicator.

Why does ScrollDirection need 'use client' while the header doesn't? Because it's the only one that needs useEffect and browser APIs. I wrote about the 'use client' boundary at length in Learning Next.js 16, and the use client docs describe it as the entry point from server to client. This component returns null, so the only thing shipped to the browser is its small piece of logic.

Step 3: Knowing When the Reader Is Inside the Article

The easiest way to know whether the reader has passed the title is to call getBoundingClientRect() on every scroll event. It works, but it forces the browser to keep calculating element positions on the main thread. The Intersection Observer API was made for exactly this problem: the browser does the watching, and we only get notified when something changes.

The trick is to place two empty marker elements on the page. One right after the article header, and another right after the article body. File app/blog/[slug]/reader-bar.tsx:

TypeScript
'use client'

import { useEffect, useState } from 'react'

const sizes = [
  { key: 'm', label: 'normal' },
  { key: 'l', label: 'large' },
  { key: 'xl', label: 'extra large' },
] as const

export function ReaderBar({ title }: { title: string }) {
  const [inside, setInside] = useState(false)
  const [size, setSize] = useState(0)
  const [copied, setCopied] = useState(false)

  useEffect(() => {
    const start = document.querySelector('[data-reader-start]')
    const end = document.querySelector('[data-reader-end]')
    if (!start || !end) return

    const seen = new Map<Element, IntersectionObserverEntry>()
    const observer = new IntersectionObserver((entries) => {
      for (const entry of entries) seen.set(entry.target, entry)
      const a = seen.get(start)
      const b = seen.get(end)
      if (!a || !b) return
      const passedStart = !a.isIntersecting && a.boundingClientRect.top < 0
      const beforeEnd = !b.isIntersecting && b.boundingClientRect.top > 0
      setInside(passedStart && beforeEnd)
    })

    observer.observe(start)
    observer.observe(end)
    return () => observer.disconnect()
  }, [])

  useEffect(() => {
    const root = document.documentElement
    root.dataset.size = sizes[size].key
    return () => {
      delete root.dataset.size
    }
  }, [size])

  const share = async () => {
    const url = window.location.href
    if (typeof navigator.share === 'function') {
      await navigator.share({ title, url }).catch(() => null)
      return
    }
    await navigator.clipboard.writeText(url)
    setCopied(true)
    window.setTimeout(() => setCopied(false), 1800)
  }

  const toTop = () => {
    const calm = window.matchMedia('(prefers-reduced-motion: reduce)').matches
    window.scrollTo({ top: 0, behavior: calm ? 'instant' : 'smooth' })
    document.getElementById('title')?.focus({ preventScroll: true })
  }

  return (
    <div className="reader-bar" role="group" aria-label="Reading tools" data-sticky data-shown={inside || undefined} inert={!inside}>
      <button type="button" onClick={() => setSize((s) => (s + 1) % sizes.length)} aria-label={`Text size: ${sizes[size].label}`}>
        aA
      </button>
      <button type="button" onClick={share} aria-label="Share">
        <svg viewBox="0 0 20 20" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.6" aria-hidden="true">
          <path d="M10 3v10M6 7l4-4 4 4M4 12v4h12v-4" />
        </svg>
      </button>
      <button type="button" onClick={toTop} aria-label="Back to top">
        <svg viewBox="0 0 20 20" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.6" aria-hidden="true">
          <path d="M10 16V5M5 9l5-5 5 5" />
        </svg>
      </button>
      <p role="status" className="reader-toast">
        {copied ? 'Link copied. Send it to the group chat, not just your saved messages.' : ''}
      </p>
    </div>
  )
}

The logic in the callback is short, but worth reading slowly. The reader counts as inside the article when the start marker has already passed above the screen and the end marker is still below it. As soon as the end marker enters the screen, the toolbar steps aside, because the comments section below it needs the space.

The toolbar only shows inside the article body and follows scroll direction, then hides before the title and after the article ends

The Map called seen exists because the IntersectionObserver callback only receives entries that changed. If only the end marker changed, we still need the last known state of the start marker to make a decision.

When the toolbar is outside the article, it gets the inert attribute. According to MDN on the inert attribute, inert elements can't be focused or clicked and are removed from the accessibility tree. So buttons that aren't visible also can't be reached by keyboard or screen reader users. In React 19, inert works directly as a boolean prop.

The share button uses navigator.share when it's available, usually on phones, and falls back to the clipboard otherwise. The confirmation message lives in a role="status" element so screen readers announce it too.

The back to top button moves focus to the title after scrolling, because the button itself is about to become inert. If focus stayed there, the browser would throw it to <body>, and keyboard users would have to start tabbing from the very beginning again.

The article page, file app/blog/[slug]/page.tsx:

TypeScript
import type { Metadata } from 'next'
import { notFound } from 'next/navigation'
import { Suspense } from 'react'
import { getPost, getPosts } from '@/lib/posts'
import { ReaderBar } from './reader-bar'

export async function generateStaticParams() {
  const posts = await getPosts()
  return posts.map((post) => ({ slug: post.slug }))
}

export async function generateMetadata({ params }: PageProps<'/blog/[slug]'>): Promise<Metadata> {
  const { slug } = await params
  const post = await getPost(slug)
  return post ? { title: post.title, description: post.excerpt } : {}
}

export default function Page({ params }: PageProps<'/blog/[slug]'>) {
  return (
    <Suspense fallback={<p className="article">Loading article…</p>}>
      <Article params={params} />
    </Suspense>
  )
}

async function Article({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params
  const post = await getPost(slug)
  if (!post) notFound()

  return (
    <main className="article">
      <header>
        <h1 id="title" tabIndex={-1}>
          {post.title}
        </h1>
        <p className="excerpt">{post.excerpt}</p>
      </header>
      <div data-reader-start aria-hidden="true" />
      <div className="prose" dangerouslySetInnerHTML={{ __html: post.html }} />
      <div data-reader-end aria-hidden="true" />
      <section aria-labelledby="comments" className="comments">
        <h2 id="comments">Comments</h2>
        <p>No comments yet. Quieter than the class group chat after graduation.</p>
      </section>
      <ReaderBar title={post.title} />
    </main>
  )
}

The Suspense pattern here is the same one I used in the previous Next.js post. params is only awaited inside the Suspense boundary so the page skeleton still makes it into the static shell. Replace getPost and getPosts with your own data source. The h1 gets tabIndex={-1} so it can receive focus from the back to top button without joining the Tab order.

Step 4: The CSS That Runs the Show

File app/globals.css:

CSS
:root {
  --paper: #ffffff;
  --ink: #111111;
  --lime: #e5ff11;
  --ease: cubic-bezier(0.22, 1, 0.36, 1);
}

html {
  scroll-padding-block: 4.5rem 6rem;
}

body {
  margin: 0;
  background: var(--paper);
  color: var(--ink);
  font-family: system-ui, sans-serif;
}

.site-header {
  position: sticky;
  top: 0;
  z-index: 20;
  display: flex;
  height: 3.5rem;
  align-items: center;
  justify-content: space-between;
  padding-inline: 1rem;
  border-bottom: 1px solid rgb(0 0 0 / 0.08);
  background: rgb(255 255 255 / 0.94);
  transition: translate 300ms var(--ease);
}

:root[data-scroll='down'] .site-header {
  translate: 0 -100%;
}

.reader-bar {
  position: fixed;
  bottom: max(1rem, env(safe-area-inset-bottom));
  left: 50%;
  z-index: 30;
  display: flex;
  gap: 0.25rem;
  padding: 0.375rem;
  border: 1px solid rgb(0 0 0 / 0.08);
  border-radius: 0.5rem;
  background: rgb(255 255 255 / 0.94);
  box-shadow: 0 8px 32px rgb(0 0 0 / 0.12);
  opacity: 0;
  translate: -50% calc(100% + 1.5rem);
  transition:
    translate 300ms var(--ease),
    opacity 200ms;
}

.reader-bar[data-shown] {
  opacity: 1;
  translate: -50% 0;
}

:root[data-scroll='down'] .reader-bar[data-shown] {
  opacity: 0;
  translate: -50% calc(100% + 1.5rem);
}

@supports (backdrop-filter: blur(1px)) {
  .site-header,
  .reader-bar {
    background: rgb(255 255 255 / 0.72);
    backdrop-filter: saturate(180%) blur(20px);
  }
}

.reader-bar button {
  display: grid;
  min-width: 2.75rem;
  height: 2.75rem;
  place-items: center;
  border: 0;
  border-radius: 0.3125rem;
  background: transparent;
  color: inherit;
  font: 600 0.9375rem/1 system-ui, sans-serif;
  cursor: pointer;
}

.reader-bar button:hover,
.reader-bar button:active {
  background: var(--lime);
}

.reader-bar button:focus-visible {
  outline: 2px solid var(--ink);
  outline-offset: 2px;
}

.reader-toast {
  position: absolute;
  bottom: calc(100% + 0.5rem);
  left: 50%;
  margin: 0;
  padding: 0.5rem 0.75rem;
  background: var(--ink);
  color: var(--paper);
  font-size: 0.8125rem;
  white-space: nowrap;
  translate: -50% 0;
}

.reader-toast:empty {
  display: none;
}

.article {
  max-width: 42rem;
  margin: 0 auto;
  padding: 2rem 1rem 8rem;
}

.prose {
  font-size: 1.0625rem;
  line-height: 1.7;
}

:root[data-size='l'] .prose {
  font-size: 1.1875rem;
}

:root[data-size='xl'] .prose {
  font-size: 1.3125rem;
}

@media (prefers-reduced-motion: reduce) {
  .site-header,
  .reader-bar {
    transition: none;
  }
}

The toolbar is hidden with translate and opacity, not with display: none or by changing bottom. Those two properties can be animated without recalculating layout, so the motion stays smooth even when the page is busy.

There are two layers of conditions. [data-shown] from ReaderBar decides whether the toolbar is allowed to appear at all, while :root[data-scroll='down'] from ScrollDirection can hide it temporarily. If you handle both inside a single React component, you end up with a component that re-renders every time the direction changes, plus a header that has to be told through context or a store. With attributes on <html>, every element just reads the same state.

bottom: max(1rem, env(safe-area-inset-bottom)) keeps the toolbar from sinking behind the home indicator. The env() function returns 0 on regular rectangular screens, so on desktop the gap stays at 1rem.

The glass effect uses backdrop-filter wrapped in @supports, so browsers without support still get a white background that's solid enough to read on.

Oh, and here's a trap I fell into myself. The mobile menu on this site used to be only 109 pixels tall when it should have filled the whole screen. The cause was a position: fixed menu panel sitting inside a header that used backdrop-filter. It turns out an element with backdrop-filter, filter, or transform becomes the containing block for its fixed descendants, so the panel got trapped inside the header. That's why the toolbar in this tutorial is deliberately not placed inside anything with a glass effect.

The buttons are 44 pixels. WCAG 2.2 only requires a 24 pixel minimum target through the Target Size (Minimum) criterion, but this toolbar gets tapped with a thumb while walking more often than not, so I went bigger.

Don't Let the Toolbar Cover What's Focused

This is the part that's most often missing. WCAG 2.2 has criterion 2.4.11 Focus Not Obscured (Minimum) at level AA: an element receiving keyboard focus must not be entirely hidden by content we created ourselves. The example in W3C's overview of WCAG 2.2 is literally about a banner fixed to the bottom of the page.

Sticky headers and toolbars are the usual suspects. Imagine a user tabbing to a link in the last paragraph on screen. The browser scrolls that link right up against the edge of the viewport, and that's exactly where our toolbar lives.

The fix is already in the first rule of the CSS above:

CSS
html {
  scroll-padding-block: 4.5rem 6rem;
}

scroll-padding tells the browser there's an area at the top and bottom of the viewport that's covered. When the browser scrolls a focused element into view, it leaves that space, so the element stops above the toolbar instead of behind it. The numbers match the header and toolbar heights, plus a little breathing room.

Without scroll-padding, the focused link is hidden behind the toolbar; with scroll-padding, the browser stops right above it

Try this: open one of your articles, click an empty area at the very top, then press Tab over and over without touching the mouse. If even one link loses its focus ring behind the header or toolbar, your scroll-padding needs to grow.

Can You Do It With CSS Only?

Yes, but not in every browser yet. Chrome 144, released on January 13, 2026, added support for scrolled in scroll-state container queries, according to the Chrome 144 release notes. With it, CSS can know the last scroll direction without any JavaScript:

CSS
html {
  container-type: scroll-state;
}

@container scroll-state(scrolled: block-end) {
  .site-header {
    translate: 0 -100%;
  }
}

I tried it in Chromium 153. The header hid as soon as I scrolled down and came back when I scrolled up. The full syntax is explained in MDN's guide to container scroll-state queries.

But as of October 2026, Safari and Firefox don't support it. The pure CSS version also has no movement threshold, so even a 1 pixel brush counts, and it knows nothing about the article boundaries. If you want to experiment, don't combine it with the JavaScript version on the same element, because the CSS rule will hide the header even for the small movements we deliberately ignore.

Mistakes I See a Lot

The most common one is keeping scrollY in React state and calling setState on every scroll event. The component re-renders dozens of times per second when all you need is one attribute on the DOM. Let CSS do the work.

The second is a toolbar hidden with opacity: 0 alone, without inert. The buttons disappear from view, but they're still in the Tab order and still read out by screen readers.

The third is forgetting the movement threshold, so the toolbar flickers whenever the trackpad gets touched. Then there's the toolbar that keeps sitting on top of the comments or the footer, and the fixed element placed inside something with backdrop-filter or transform.

And the classic one, testing only with a mouse on your own laptop. Works on my machine, but your readers aren't your machine. Try it with a keyboard, turn on reduced motion, and open it on a phone with your thumb.

A small toolbar like this looks trivial, but it's exactly where readers feel whether a site respects their time. Start with one article page, add ScrollDirection and ReaderBar, then use it yourself for a week. The right threshold and offset usually show up after real use, not after overthinking it.

Thanks for reading all the way down here. If the toolbar at the bottom of your screen just popped up when you scrolled back to check the code, it's doing exactly what it's supposed to.

Hafidz Nc

Fractional Head of Digital

Discussion