Underline Tabs With Sliding Indicator
Four tabs for a coworking space listing: Overview, Amenities, Pricing and Location. A thin blue line under the labels slides and stretches to fit whichever tab is chosen, and each panel holds a heading and a short paragraph. On a narrow phone the row scrolls sideways and the chosen tab is scrolled into view.
Code
import { useEffect, useRef, useState, type KeyboardEvent } from "react";
// Tabs and their panels. Edit labels and content here.
const tabs = [
{ id: "overview", label: "Overview", title: "A quiet room above the harbour", body: "Twelve desks, two phone booths and a meeting room for six, a short walk from the ferry terminal. Open from 7am to 9pm on weekdays." },
{ id: "amenities", label: "Amenities", title: "What is included", body: "Fibre broadband, a kitchen with proper coffee, lockers, printing, showers and secure bike storage in the courtyard." },
{ id: "pricing", label: "Pricing", title: "From $240 a month", body: "Flexible desks are $240, a fixed desk is $360 and a day pass is $28. No setup fee and one month's notice." },
{ id: "location", label: "Location", title: "4 Wharf Lane, upstairs", body: "Two minutes from the ferry, five from the main bus stops. Street parking after 6pm and a loading bay for deliveries." },
];
export default function UnderlineTabsWithSlidingIndicator() {
const [active, setActive] = useState(0);
const refs = useRef<(HTMLButtonElement | null)[]>([]);
const list = useRef<HTMLDivElement>(null);
const [bar, setBar] = useState({ x: 0, w: 0 });
useEffect(() => {
const measure = () => {
const el = refs.current[active];
if (el) setBar({ x: el.offsetLeft, w: el.offsetWidth });
};
measure();
const ro = new ResizeObserver(measure);
if (list.current) ro.observe(list.current);
return () => ro.disconnect();
}, [active]);
// Keep the chosen tab visible when the row scrolls sideways on phones (not on first render).
const first = useRef(true);
useEffect(() => {
if (first.current) { first.current = false; return; }
refs.current[active]?.scrollIntoView({ block: "nearest", inline: "nearest" });
}, [active]);
const onKey = (e: KeyboardEvent<HTMLDivElement>) => {
const last = tabs.length - 1;
const next = { ArrowRight: active === last ? 0 : active + 1, ArrowLeft: active === 0 ? last : active - 1, Home: 0, End: last }[e.key];
if (next === undefined) return;
e.preventDefault();
setActive(next);
refs.current[next]?.focus();
};
return (
<div className="bg-white px-4 py-12 sm:px-8">
<div className="mx-auto max-w-2xl">
<div className="relative overflow-x-auto">
<div ref={list} role="tablist" aria-label="Harbour Loft workspace" onKeyDown={onKey} className="relative flex gap-6 border-b border-slate-200">
{tabs.map((t, i) => (
<button
key={t.id}
ref={(el) => { refs.current[i] = el; }}
id={`ust-tab-${t.id}`}
role="tab"
type="button"
aria-selected={i === active}
aria-controls={`ust-panel-${t.id}`}
tabIndex={i === active ? 0 : -1}
onClick={() => setActive(i)}
className={`h-12 whitespace-nowrap rounded-t px-1 text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-600 ${i === active ? "text-slate-900" : "text-slate-600 hover:text-slate-900"}`}
>
{t.label}
</button>
))}
<span
aria-hidden="true"
className="absolute bottom-[-1px] left-0 h-0.5 w-[100px] origin-left rounded-full bg-blue-600 transition-transform duration-300 ease-out motion-reduce:transition-none"
style={{ transform: `translateX(${bar.x}px) scaleX(${bar.w / 100})` }}
/>
</div>
</div>
{tabs.map((t, i) => (
<div key={t.id} id={`ust-panel-${t.id}`} role="tabpanel" aria-labelledby={`ust-tab-${t.id}`} tabIndex={0} hidden={i !== active} className="rounded-lg pt-8 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-600">
<h3 className="text-2xl font-semibold tracking-tight text-slate-900">{t.title}</h3>
<p className="mt-3 max-w-prose leading-7 text-slate-600">{t.body}</p>
</div>
))}
</div>
</div>
);
}
Install with one command: npx shadcn@latest add https://we.inc/r/underline-tabs-with-sliding-indicator.json
When to use it
- A page has three to six sections of equal weight that people read one at a time.
- You need tabs that sit quietly under a heading without boxes or backgrounds around each label.
- Tab labels differ in length and the indicator should match each one exactly.
- Keyboard users and screen reader users must be able to operate the tabs the standard way.
How to customize it
- Edit the `tabs` array to change labels and panel text; ids are used to link each tab to its panel.
- Change the indicator colour from `bg-blue-600` (or `--ust-accent`) and its thickness from `h-0.5`.
- Set the spacing between labels with `gap-6`; tighter gaps suit five or more tabs.
- Slow the glide by raising `duration-300`; the indicator only moves with transform, so longer values stay smooth.
Accessibility
- Uses role tablist, tab and tabpanel with aria-selected, aria-controls and aria-labelledby wired both ways.
- Left and Right arrows wrap around the row, Home and End jump to the ends, and only the chosen tab has tabindex 0.
- Panels are focusable so Tab moves from the row straight into the content.
Questions
How does the underline know where to go?
After each change, the component reads the chosen button's offsetLeft and offsetWidth, then sets a translateX and a scaleX on a 100px bar. A ResizeObserver repeats the measurement when the row changes size, for example when a web font loads.
Why scale a fixed bar instead of animating its width?
Width changes force layout on every frame of the transition. Scaling a bar with transform-origin set to the left edge gives the same visual result while the browser only composites a layer.
Can I use links instead of buttons for the tabs?
If each tab should change the URL, use links and drop the tab roles, since that is page navigation rather than tabs. Keep buttons and roles when the panels switch in place.
How do I open a tab from the URL hash?
On mount, read location.hash, find the matching id in `tabs` and pass its index to the initial state. Update the hash in the click handler with history.replaceState so the back button is not flooded.
Related: React Tabs with Sliding Underline, Segmented Pills, Vertical and Icon Count Variants, Page Tabs With Gliding Underline and Rising Content, App Sidebar With Nested Groups and Active Item.
More tabs and navigation or all free UI components. Build your site free to have a full site built around it.
More in Navigation
- Woven Ribbon Tab Bar with a Thread Marker That Unpicks and Restitches Itself
- App Sidebar With Nested Groups and Active Item
- Brass Lift Floor Indicator Navigation with an Arrow That Sweeps an Enamel Dial Between Sections
- Cast Iron Finger Post Navigation with Painted Arms That Swing Round the Post to Point at the Chosen Page
- Cloth Bound Book Spine Chapter Menu Where the Chosen Volume Leaves the Shelf and Opens at Its Chapter
- CSS Tabs Collection with Radio, :target and Accessible ARIA Tabs in Six Styles
- Enamel Platform Sign Breadcrumbs Hanging from Rail Trolleys That Roll Away Swinging When You Step Back Up the Trail
- Glazed Ceramic Tile Tabs in WebGL Leaning on a Sunlit Plaster Shelf Where the Chosen Tile Rocks Upright into the Window Light
Product
Who It's For
- For Agencies
- For Freelancers
- For Hosting Providers
- For SaaS Platforms
- For Startups
- For Financial Services
- For Healthcare
Features
Resources
- Blog
- Help Center
- Free Business Tools
- Free UI Components
- Website Templates
- Template Collections
- Website Examples
- Guides
- Comparisons
- Alternatives
- Best Lists
- Reviews
- Pricing Guides
- Use Cases
- Glossary & Guides
- Integrations
- Developers
- Benchmark
- Windows App