Launch sale: 40% off everything with code LAUNCH40 — applied automatically at checkout · ends 2026-12-19

2026-12-14 · Blog

Build an accessible filterable portfolio grid with Tailwind CSS v4 and 30 lines of vanilla JS

Most portfolio sites have a "Work" page with buttons like All / Brand / Editorial / Photo. Many of them are built with a filtering library, or with <div>s that look like buttons but aren't reachable by keyboard. You don't need either. This tutorial builds the whole thing with semantic HTML, Tailwind CSS v4 utilities and about 30 lines of plain JavaScript:

  • real <button>s that announce their state with aria-pressed
  • styling driven by that same attribute, so the state and the look can't drift apart
  • a live "8 projects" count for screen-reader users
  • shareable links like /work.html#photo
  • a short fade-in that switches itself off for people who set reduce motion

1. The markup

Each card lists its categories in a data-category attribute, space-separated, so one project can sit in two groups. Each button names the category it shows in data-filter.

<section aria-labelledby="work-title" class="mx-auto max-w-6xl px-6 py-16">
  <h1 id="work-title" class="text-4xl font-semibold tracking-tight">Work</h1>

  <div role="group" aria-label="Filter projects" class="mt-8 flex flex-wrap gap-2">
    <button type="button" data-filter="all" aria-pressed="true" class="chip">All</button>
    <button type="button" data-filter="brand" aria-pressed="false" class="chip">Brand</button>
    <button type="button" data-filter="editorial" aria-pressed="false" class="chip">Editorial</button>
    <button type="button" data-filter="photo" aria-pressed="false" class="chip">Photo</button>
  </div>

  <p data-count aria-live="polite" class="mt-4 text-sm text-zinc-500"></p>

  <ul class="mt-6 grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
    <li data-category="brand" class="card">
      <a href="/work/harbour-bakery.html" class="block">
        <img src="/img/harbour.jpg" alt="" class="aspect-4/3 w-full rounded-xl object-cover">
        <h2 class="mt-3 font-medium">Harbour Bakery identity</h2>
        <p class="text-sm text-zinc-500">Brand</p>
      </a>
    </li>
    <li data-category="editorial photo" class="card">
      <a href="/work/quiet-coast.html" class="block">
        <img src="/img/coast.jpg" alt="" class="aspect-4/3 w-full rounded-xl object-cover">
        <h2 class="mt-3 font-medium">Quiet Coast magazine feature</h2>
        <p class="text-sm text-zinc-500">Editorial, Photo</p>
      </a>
    </li>
    <!-- more cards -->
  </ul>
</section>

A few deliberate choices:

  • type="button" so the buttons never submit a surrounding form.
  • role="group" with an aria-label tells assistive tech these buttons belong together.
  • A <ul> of cards, so screen readers announce "list, 8 items", which updates as items are hidden.
  • alt="" on the thumbnail, because the heading inside the same link already names the project. Giving the image alt text too would make screen readers read the title twice.

2. Styling the state with Tailwind v4

Tailwind v4 ships aria-* variants out of the box. aria-pressed:bg-zinc-900 applies only when the element has aria-pressed="true". That means the button's look comes straight from its accessible state. If the JS sets the attribute, the style follows. There is no separate .active class to forget.

Put this in your main CSS file:

@import "tailwindcss";

@theme {
  --animate-fade-in: fade-in 0.25s ease-out;

  @keyframes fade-in {
    from { opacity: 0; transform: translateY(6px); }
    to   { opacity: 1; transform: none; }
  }
}

@layer components {
  .chip {
    @apply rounded-full border border-zinc-300 px-4 py-2 text-sm transition-colors
           hover:border-zinc-900
           focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-zinc-900
           aria-pressed:border-zinc-900 aria-pressed:bg-zinc-900 aria-pressed:text-white;
  }
  .card {
    @apply motion-safe:animate-fade-in;
  }
}

Defining --animate-fade-in inside @theme creates the animate-fade-in utility, and the @keyframes block next to it gets output with it. Wrapping it in motion-safe: means it only runs inside @media (prefers-reduced-motion: no-preference). Visitors who asked their OS for less motion get an instant switch instead.

There's a nice side effect. A CSS animation restarts whenever an element goes from display: none back to being displayed. So every card that reappears after a filter click fades in again, with no JavaScript animation code at all.

If you prefer not to use @apply, put the same utilities directly on each button. The result is identical.

3. The JavaScript (about 30 lines)

<script>
(() => {
  const buttons = document.querySelectorAll("[data-filter]");
  const cards = document.querySelectorAll("[data-category]");
  const count = document.querySelector("[data-count]");
  if (!buttons.length || !cards.length) return;

  const names = [...buttons].map((b) => b.dataset.filter);

  function apply(name, updateUrl) {
    if (!names.includes(name)) name = "all";
    let shown = 0;

    buttons.forEach((b) => b.setAttribute("aria-pressed", String(b.dataset.filter === name)));
    cards.forEach((card) => {
      const match = name === "all" || card.dataset.category.split(" ").includes(name);
      card.hidden = !match;
      if (match) shown++;
    });

    if (count) count.textContent = `${shown} ${shown === 1 ? "project" : "projects"}`;
    if (updateUrl) history.replaceState(null, "", name === "all" ? location.pathname : `#${name}`);
  }

  buttons.forEach((b) => b.addEventListener("click", () => apply(b.dataset.filter, true)));
  window.addEventListener("hashchange", () => apply(location.hash.slice(1), false));
  apply(location.hash.slice(1), false);
})();
</script>

What each part does:

  • names is the list of valid filters. A hash like #typo or #<script> falls back to "all" instead of hiding everything.
  • aria-pressed is set on every button on every click. Exactly one is ever "true", and that drives both the screen-reader state and the Tailwind style.
  • card.hidden uses the native hidden attribute. Tailwind v4's base styles make [hidden] reliably display: none. Hidden cards also drop out of the tab order and the accessibility tree, so keyboard users never tab into invisible links.
  • The count sits in an aria-live="polite" region. After a click, screen readers say "3 projects" without moving focus.
  • history.replaceState updates the URL to #photo without adding a history entry for every click. The Back button still leaves the page instead of stepping through filters. Remove updateUrl if you don't want shareable links.
  • hashchange handles in-page links like <a href="#editorial">See editorial work</a> elsewhere on the page.

4. Optional: a smoother swap with the View Transitions API

Chromium-based browsers and Safari support document.startViewTransition(). It cross-fades the old grid layout into the new one, so the cards slide into place instead of jumping. Change the click handler to:

const reduce = window.matchMedia("(prefers-reduced-motion: reduce)");

buttons.forEach((b) => b.addEventListener("click", () => {
  const run = () => apply(b.dataset.filter, true);
  if (document.startViewTransition && !reduce.matches) document.startViewTransition(run);
  else run();
}));

Browsers without the API just run the filter instantly, and reduced-motion users skip the transition entirely. Nothing breaks either way.

5. Testing checklist

Before you ship it, try these in under five minutes:

  1. Keyboard only: Tab to the buttons, press Enter or Space, and Tab into the grid. You should never land on a hidden card.
  2. Screen reader (VoiceOver: Cmd+F5, NVDA on Windows): a button should read "Photo, toggle button, pressed", and the count should be announced after each click.
  3. Reduced motion: in Chrome DevTools, open the Rendering panel and set Emulate CSS media feature prefers-reduced-motion to reduce. Cards should appear instantly.
  4. Deep link: open /work.html#photo in a new tab. The Photo filter should already be active.
  5. No JavaScript: disable JS and reload. Every project should still be visible, because nothing is hidden until the script runs.

That last point is why the cards start without hidden in the HTML. The filter is an enhancement on top of a page that already works.

The full template

This grid is taken from Atelier, an editorial portfolio template I made and sell. It's plain HTML and Tailwind CSS v4 with six pages (home, filterable work archive with live counts, case study, about, contact, 404), a light/dark toggle, and a page-enter animation that respects reduced motion. You re-theme the whole site with three CSS variables. It's here: https://najoomi-templates.najoomi.workers.dev/t/atelier-portfolio/

Launch sale: 40% off with code LAUNCH40 until 19 Dec (applied automatically from the store page).

Disclosure: I run the store that sells Atelier. The code in this article is complete and free to use in your own projects.

More templates like this

Excel & Google Sheets templates, planners, website templates and AI kits.

Browse the catalog