Skip to content
Star

Segmented control

Switch between views of the same thing, with a sliding indicator. Free and MIT licensed, as HTML, a typed React component or an Astro component, in three styles with light and dark mode.

$npx designme add segmented-control
$npx shadcn@latest add https://designme.dev/r/shadcn/segmented-control.json

Need this designed into your product? Book a call

October 2026
01

Install

Add it to your project with the CLI.

HTML, CSS and JS

$npx designme add segmented-control

React

$npx designme add segmented-control --react

Astro

$npx designme add segmented-control --astro

shadcn, React

$npx shadcn@latest add https://designme.dev/r/shadcn/segmented-control.json

shadcn, Astro

$npx shadcn@latest add https://designme.dev/r/shadcn/astro/segmented-control.json

The CLI copies the source into your project, so you own it and can change anything. Where each version lands, what it needs and the shadcn theme bridge: Installation.

02

About

What it is for and what it does.

Segmented control is a row of two to five choices where exactly one is picked, shown as a raised knob that slides to it. Use it to switch between views of the same thing, like a calendar and a list, or to set one option from a few. It sits inline next to a title and changes what's below it at once. An option can be an icon alone, with its name as the label and a tooltip.

  • When people switch between a few views of the same content, like a calendar and a list of the same month.
  • When there are two to five short options and all of them should stay visible.
  • When the change should happen at once, without a separate Apply.
  • Not for more than five options, or long labels: use a select or tabs with an overflow then.
03

Usage

Import it in React and drive it from your own state, or place it in an Astro page.

React

import { SegmentedControl } from '@/components/designme/segmented-control/SegmentedControl';

React example

The demo above as a React component, 131 lines you can copy.

'use client';
// The animated preview from designme.dev, rebuilt from the React component: an example of driving it from your own state.
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
import { SegmentedControl } from './SegmentedControl';
import { cx } from '../lib/cx';
import { Icon } from '../lib/icons';
import { mxIn, Swap, Tip, useGrow } from '../lib/motion';
import { useStory } from '../lib/useScript';
import { useHoverGlide } from '../lib/glide';

/* ---------- Segmented control: a month of a pricing launch, as a calendar or a list ---------- */
type View = 'list' | 'cal';
type Ev = [day: string, name: string, time: string, launch?: boolean];
// October 2026: today is Friday the 23rd, and the launch on the 28th is the one accent mark
const TODAY = '2026-10-23';
const EV: Ev[] = [['2026-10-06', 'Kickoff', '10:00'], ['2026-10-09', 'Brief review', '14:00'], ['2026-10-14', 'Copy review', '11:00'], ['2026-10-20', 'Design sign-off', '16:00'], ['2026-10-26', 'QA pass', '09:30'], ['2026-10-28', 'Pricing goes live', '10:00', true]];
const pad = (n: number) => String(n).padStart(2, '0');
const iso = (d: Date) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
const day = (k: string) => { const [y, m, d] = k.split('-').map(Number); return new Date(y, m - 1, d, 12); };
const fmt = (d: Date, o: Intl.DateTimeFormatOptions) => d.toLocaleDateString('en-US', o);
const short = (k: string) => fmt(day(k), { month: 'short', day: 'numeric' });
const ev = (k: string) => EV.find(e => e[0] === k);
const inMonth = (m: Date) => EV.filter(e => e[0].startsWith(iso(m).slice(0, 7)));
// a month's picked day when you step to it: the launch, else its first event, else the 1st
const firstPick = (m: Date) => { const L = inMonth(m); return (L.find(e => e[3]) ?? L[0])?.[0] ?? iso(m); };

// the calendar: a calm month, a grey dot on a day with something on (the launch's dot in the accent), today a quiet ring and the
// picked day a small accent circle; under a hairline, the picked day's line
function Calendar({ month, sel, pick }: { month: Date; sel: string; pick: (k: string) => void }) {
  const lead = (month.getDay() + 6) % 7, len = new Date(month.getFullYear(), month.getMonth() + 1, 0).getDate(), e = ev(sel);
  return (
    <div className="dm-sgc-cal">
      <div className="dm-sgc-mo">
        {['M', 'T', 'W', 'T', 'F', 'S', 'S'].map((w, i) => <span key={'w' + i} className="dm-w" aria-hidden="true">{w}</span>)}
        {Array.from({ length: lead }, (_, i) => <span key={'b' + i} />)}
        {Array.from({ length: len }, (_, i) => {
          const d = new Date(month.getFullYear(), month.getMonth(), i + 1, 12), k = iso(d), x = ev(k), on = k === sel;
          return (
            <button key={k} type="button" aria-pressed={on} aria-label={`${fmt(d, { weekday: 'long', month: 'long', day: 'numeric' })}, ${x ? x[1] : 'nothing planned'}`} onClick={() => pick(k)}
              className={cx('dm-d dm-num', x && 'dm-e', x?.[3] && 'dm-x', k === TODAY && 'dm-now', on && 'dm-on')}><b>{i + 1}</b></button>
          );
        })}
      </div>
      <div className="dm-sgc-sel" aria-live="polite">
        <Swap className="dm-num">{short(sel)}</Swap>
        {e ? <span className="dm-t">{e[1]} <span>· {e[2]}</span></span> : <span className="dm-t dm-none">Nothing planned</span>}
        {e?.[3] && <i className="dm-x" />}
      </div>
    </div>
  );
}

// the list: the month's events as rows, a row opening its day in the calendar
function List({ month, open }: { month: Date; open: (k: string) => void }) {
  const L = inMonth(month);
  return L.length ? (
    <div className="dm-sgc-ls">
      {L.map(e => (
        <button key={e[0]} type="button" className="dm-sgc-lr" onClick={() => open(e[0])}>
          <span className="dm-num">{short(e[0])}</span>
          <span className="dm-t"><span>{e[1]}</span>{e[3] && <i className="dm-x" />}</span>
          <span className="dm-num dm-tm">{e[2]}</span>
        </button>
      ))}
    </div>
  ) : <div className="dm-sgc-none">Nothing planned this month</div>;
}

export default function SegmentedControlDemo() {
  const ref = useRef<HTMLDivElement>(null);
  const [view, setView] = useState<View>('cal');
  const [month, setMonth] = useState(() => new Date(2026, 9, 1, 12));
  const [sel, setSel] = useState('2026-10-28');
  // the view on show, and the one it replaced while that fades out under the new one, so no frame is empty
  const key = view + iso(month);
  const [layers, setLayers] = useState([{ key, view, month, gone: false }]);
  if (layers[layers.length - 1].key !== key) setLayers([...layers.filter(l => !l.gone).slice(-1).map(l => ({ ...l, gone: true })), { key, view, month, gone: false }]);
  useEffect(() => {
    if (!layers.some(l => l.gone)) return;
    const t = setTimeout(() => setLayers(ls => ls.filter(l => !l.gone)), 240);
    return () => clearTimeout(t);
  }, [layers]);
  // the new view's days or rows come in one after another
  const fresh = useRef<HTMLDivElement>(null), first = useRef(true);
  useLayoutEffect(() => {
    if (first.current) { first.current = false; return; }
    const el = fresh.current; if (!el) return;
    const days = Array.from(el.querySelectorAll('.dm-sgc-mo .dm-d'));
    if (days.length) mxIn([...days, el.querySelector('.dm-sgc-sel')], { ms: 300, step: 6, y: 4 });
    else mxIn(Array.from(el.querySelectorAll('.dm-sgc-lr')), { ms: 300, step: 40, y: 4 });
  }, [key]);
  const step = (k: number) => { const m = new Date(month.getFullYear(), month.getMonth() + k, 1, 12); setMonth(m); setSel(firstPick(m)); };
  const open = (k: string) => { setSel(k); setView('cal'); };
  // the panel is as tall as the view on show and eases to the next one's height
  const [panel, panelIn] = useGrow();
  // Studio's one hover: a highlight that glides from row to row in the list
  useHoverGlide(panel, '.dm-sgc-lr');

  // the preview's story, calm: the calendar, the list, and back to the calendar
  useStory(ref, async ({ wait, press }) => {
    await wait(2000); press('[data-v="list"]');
    await wait(2500); press('[data-v="cal"]');
  });

  return (
    <div ref={ref} style={{ width: '100%' }}>
      <div data-dm="" className="dm-sgc dm-panel" data-v={view}>
        {/* one line: the month as the title between two quiet chevrons, and the switch, two icons, on the right */}
        <div className="dm-sgc-h">
          <div className="dm-sgc-mt">
            <Tip label="Previous month"><button type="button" className="dm-ib dm-sgc-pv" aria-label="Previous month" onClick={() => step(-1)}><Icon name="chev-l" size="xs" /></button></Tip>
            <b className="dm-sgc-r" aria-live="polite"><Swap>{fmt(month, { month: 'long', year: 'numeric' })}</Swap></b>
            <Tip label="Next month"><button type="button" className="dm-ib dm-sgc-nx" aria-label="Next month" onClick={() => step(1)}><Icon name="chev-r" size="xs" /></button></Tip>
          </div>
          <SegmentedControl id="launch-view" label="View" value={view} onValueChange={setView}
            options={[{ value: 'list', label: <Icon name="list" size="s" />, title: 'List' }, { value: 'cal', label: <Icon name="cal" size="s" />, title: 'Calendar' }]} />
        </div>
        <div ref={panel} className="dm-sgc-p dm-growing" id="launch-view-panel" role="tabpanel" aria-labelledby={`launch-view-${view}`} tabIndex={0}>
          <div ref={panelIn} className="dm-grow">
            {layers.map((l, i) => (
              <div key={l.key} ref={l.gone ? undefined : fresh} className={cx('dm-sgc-in', l.gone ? 'dm-gone' : i > 0 && 'dm-fresh')} inert={l.gone} aria-hidden={l.gone || undefined}>
                {l.view === 'cal' ? <Calendar month={l.month} sel={sel} pick={setSel} /> : <List month={l.month} open={open} />}
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

Astro

In a page in src/pages. It plays the demo above; change its segmented-control.js to show your own data. Attributes like class go on its root element.

---
import SegmentedControl from '../components/designme/segmented-control/SegmentedControl.astro';
---
<SegmentedControl />
<SegmentedControl data-style="soft" class="my-class" />
04

Props

Everything SegmentedControl takes.

PropTypeWhat it does
optionsrequiredSegmentOption<T>[]
valueT
defaultValueT
onValueChange(value: T) => void
labelrequiredstringNames the group for screen readers, like "View"
as'tabs' | 'radio'`tabs` (the default) when it switches a panel, `radio` when it sets an option
idstringTies the tabs to their panel: put `id={`${id}-panel`}` and `aria-labelledby={`${id}-${value}`}` on the panel. Defaults to a generated id
classNamestring

Also takes the props of string = string>.

05

Code

The full source, as the CLI installs it.

SegmentedControl.tsxReact · 81 lines
'use client';
import { useId, useRef, useState, type CSSProperties, type KeyboardEvent, type ReactNode } from 'react';
import { cx } from '../lib/cx';
import { useControllable, useIsoLayoutEffect } from '../lib/hooks';
import { Tip } from '../lib/motion';
import '../designme.css';
import './segmented-control.css';

export interface SegmentOption<T extends string = string> {
  value: T;
  label: ReactNode;
  /** The option's name when `label` is only an icon, like "Calendar": its aria-label and its tooltip */
  title?: string;
}

export interface SegmentedControlProps<T extends string = string> {
  options: SegmentOption<T>[];
  value?: T;
  defaultValue?: T;
  onValueChange?: (value: T) => void;
  /** Names the group for screen readers, like "View" */
  label: string;
  /** `tabs` (the default) when it switches a panel, `radio` when it sets an option */
  as?: 'tabs' | 'radio';
  /** Ties the tabs to their panel: put `id={`${id}-panel`}` and `aria-labelledby={`${id}-${value}`}` on the panel. Defaults to a generated id */
  id?: string;
  className?: string;
}

/** One choice from a few views or options, with a white knob that slides to the picked one. As tabs, the arrow keys
    move along and pick, and Home and End jump to the ends; as a radio group, the arrow keys do the same. */
export function SegmentedControl<T extends string = string>({ options, value, defaultValue, onValueChange, label, as = 'tabs', id, className }: SegmentedControlProps<T>) {
  const auto = useId();
  const base = id ?? 'dm-sgc' + auto.replace(/:/g, '');
  const [cur, setCur] = useControllable(value, (defaultValue ?? options[0]?.value) as T, onValueChange);
  const ref = useRef<HTMLDivElement>(null);
  const [knob, setKnob] = useState<CSSProperties>({ transition: 'none' });
  const first = useRef(true);
  // the knob takes the picked button's place and width, without sliding in on the first paint
  useIsoLayoutEffect(() => {
    const el = ref.current; if (!el) return;
    const place = () => {
      const b = el.querySelector<HTMLElement>('[data-on="true"]'); if (!b) return;
      setKnob({ left: b.offsetLeft, width: b.offsetWidth, ...(first.current ? { transition: 'none' } : {}) });
      if (first.current) requestAnimationFrame(() => { first.current = false; });
    };
    place();
    const ro = new ResizeObserver(place); ro.observe(el);
    return () => ro.disconnect();
  }, [cur, options.length]);

  const tabs = as === 'tabs';
  const onKey = (e: KeyboardEvent<HTMLDivElement>) => {
    const i = options.findIndex(o => o.value === cur);
    const to = ({ ArrowRight: i + 1, ArrowLeft: i - 1, Home: 0, End: options.length - 1 } as Record<string, number>)[e.key];
    if (to === undefined) return;
    e.preventDefault();
    const o = options[(to + options.length) % options.length];
    setCur(o.value);
    ref.current?.querySelector<HTMLElement>(`[data-v="${CSS.escape(o.value)}"]`)?.focus();
  };

  return (
    <div ref={ref} data-dm="" className={cx('dm-sgc-seg', className)} role={tabs ? 'tablist' : 'radiogroup'} aria-label={label} onKeyDown={onKey}>
      <span className="dm-sgc-k" style={knob} aria-hidden="true" />
      {options.map(o => {
        const on = o.value === cur;
        const b = (
          <button key={o.value} type="button" data-v={o.value} data-on={on} id={`${base}-${o.value}`} tabIndex={on ? 0 : -1} aria-label={o.title}
            role={tabs ? 'tab' : 'radio'} {...(tabs ? { 'aria-selected': on, 'aria-controls': `${base}-panel` } : { 'aria-checked': on })}
            onClick={() => setCur(o.value)}>
            {o.label}
          </button>
        );
        // an icon-only option is named, and shows its name in a tooltip
        return o.title ? <Tip key={o.value} label={o.title}>{b}</Tip> : b;
      })}
    </div>
  );
}
segmented-control.cssReact · 87 lines
/* Generated from designme.dev by scripts/sync.mjs. Edit the site, then sync. */
/* ---------- Segmented control ---------- */
/* one choice from a few views of the same thing: the picked one sits on a white knob that slides to it. It is a tab
   list, so the arrow keys move along it and the panel under it changes with it. The demo (owner, 28 Nov) is a month of a
   pricing launch: a one-line head, the month as the title between two quiet chevrons on the left and the switch on the right,
   two icons on the grey track (List and Calendar, each named and with a tooltip) */
.dm-sgc{width:100%;max-width:400px;margin:0 auto;padding:var(--dm-s-4);display:flex;flex-direction:column;gap:14px;transition:padding-bottom var(--dm-t) cubic-bezier(.23,1,.32,1)}
/* in the list, the last row's hover room makes up the foot, so its words still end 16px from the card's bottom */
.dm-sgc.dm-panel[data-v="list"]{padding-bottom:calc(var(--dm-s-4) - 7px)}
.dm-sgc-h{display:flex;align-items:center;justify-content:space-between;gap:var(--dm-s-3)}
/* the first chevron's glyph sits on the content's left edge, its 28px hover circle reaching out round it (the 12px glyph is
   centred in the box, so the box starts 8px further out) */
.dm-sgc-mt{display:flex;align-items:center;gap:2px;min-width:0}
.dm-sgc-mt .dm-ib{width:28px;height:28px;color:var(--dm-fg2)}
.dm-sgc-mt .dm-sgc-pv{margin-left:calc((12px - 28px) / 2)}
.dm-sgc-mt b{font-size:14px;font-weight:500;padding:0 var(--dm-s-1);white-space:nowrap}
.dm-sgc-seg{position:relative;display:inline-flex;padding:3px;border-radius:var(--dm-r-pill);background:var(--dm-chip);flex:none}
.dm-sgc-k{position:absolute;top:3px;bottom:3px;left:3px;width:0;border-radius:var(--dm-r-pill);background:var(--dm-raised);box-shadow:var(--dm-seg-k-shadow,var(--dm-shadow));transition:left .42s var(--dm-ease),width .42s var(--dm-ease)}
.dm-sgc-seg button{position:relative;z-index:1;height:30px;padding:0 14px;border-radius:var(--dm-r-pill);font-size:13px;color:var(--dm-fg2);outline:0;transition:color .2s}
.dm-sgc-seg button:has(>.dm-i:only-child){width:36px;padding:0;display:grid;place-items:center}
.dm-sgc-seg button[aria-selected="true"],.dm-sgc-seg button[aria-checked="true"]{color:var(--dm-fg)}
@media (hover:hover) and (pointer:fine){.dm-sgc-seg button:hover{color:var(--dm-fg)}}
.dm-sgc-seg button:focus-visible{box-shadow:0 0 0 2px var(--dm-focus)}
/* the panel is as tall as the view on show, and eases to the next one's height (grow()) */
.dm-sgc-p{position:relative;border-radius:var(--dm-r-in);outline:0}
.dm-sgc-p.dm-growing{overflow-clip-margin:10px}
.dm-sgc-p:focus-visible{box-shadow:0 0 0 2px var(--dm-focus)}
/* a new view crossfades over the one it replaces, so the panel is never empty between them; its days or rows come in one after
   another (mxIn), on Studio's ease in every style. With reduced motion it only swaps */
.dm-sgc-in{--dm-ease:cubic-bezier(.23,1,.32,1)}
.dm-sgc-in.dm-fresh{animation:dm-sgcin .22s var(--dm-ease) both}
.dm-sgc-in.dm-gone{position:absolute;inset:0 0 auto;pointer-events:none;animation:dm-sgcout .22s var(--dm-ease) both}
@keyframes dm-sgcin{from{opacity:0}}
@keyframes dm-sgcout{to{opacity:0}}
@media (prefers-reduced-motion:reduce){.dm-sgc-in.dm-fresh,.dm-sgc-in.dm-gone{animation:none}}
/* nothing in it grows or shrinks when it is pressed (owner, 18 Nov) */
.dm-sgc :is(.dm-ib,.dm-pill):active,:root[data-style="studio"] .dm-sgc .dm-ib:active,:root [data-style="studio"] .dm-sgc .dm-ib:active,:root [data-style="studio"].dm-sgc .dm-ib:active{transform:none}
/* the calendar: a calm month. A grey dot only on a day with something on, the launch day's dot the one accent mark; today a
   quiet grey ring; the picked day a small accent circle. Under a hairline, the picked day's line: its date, its event and time */
.dm-sgc-cal{display:flex;flex-direction:column;gap:14px}
/* the days' circles are centred in their columns, and the grid reaches out into the padding just far enough that Monday's
   circle starts and Sunday's ends on the content's edges, under the head's chevron and switch, at every width: with 7 columns
   of 26px circles and 6 gaps of 4px, each side reaches out by (circles + gaps - width) / 12 */
.dm-sgc-mo{display:grid;grid-template-columns:repeat(7,1fr);gap:2px var(--dm-s-1);margin-inline:calc((7 * 26px + 6 * var(--dm-s-1) - 100%) / 12);font-size:12px;text-align:center}
.dm-sgc-mo .dm-w{font-size:11px;color:var(--dm-muted);padding-bottom:2px}
.dm-sgc-mo .dm-d{position:relative;height:32px;display:grid;place-items:center;color:var(--dm-fg2)}
.dm-sgc-mo .dm-d b{display:grid;place-items:center;width:26px;height:26px;border-radius:50%;font-weight:400;transition:background-color var(--dm-t-fast) var(--dm-ease),color var(--dm-t-fast) var(--dm-ease),box-shadow var(--dm-t-fast) var(--dm-ease)}
@media (hover:hover) and (pointer:fine){.dm-sgc-mo .dm-d:not(.dm-on):hover b{background:var(--dm-row)}}
.dm-sgc-mo .dm-d:focus-visible{outline:0}
.dm-sgc-mo .dm-d:focus-visible b{box-shadow:0 0 0 2px var(--dm-focus)}
.dm-sgc-mo .dm-d.dm-e::after{content:"";position:absolute;bottom:0;left:50%;width:4px;height:4px;margin-left:-2px;border-radius:50%;background:var(--dm-faint)}
.dm-sgc-mo .dm-d.dm-x::after{background:var(--dm-accent-mark,var(--dm-accent))}
.dm-sgc-mo .dm-d.dm-now b{color:var(--dm-fg);box-shadow:inset 0 0 0 1px color-mix(in srgb,var(--dm-line-strong) 50%,transparent)}
.dm-sgc-mo .dm-d.dm-on b{background:var(--dm-accent);color:var(--dm-on-accent);font-weight:500;box-shadow:none}
.dm-sgc-mo .dm-d.dm-on::after{opacity:0}
/* the date, then the event 12px after it; the launch's accent dot follows the line's words, so no line keeps room for a dot
   it doesn't have */
.dm-sgc-sel{display:flex;align-items:center;gap:var(--dm-s-3);padding-top:var(--dm-s-3);border-top:1px solid color-mix(in srgb,var(--dm-line) 50%,transparent);font-size:13px;line-height:18px}
.dm-sgc-sel .dm-num{flex:none;color:var(--dm-muted)}
.dm-sgc-sel i,.dm-sgc-lr i{width:6px;height:6px;border-radius:50%;flex:none}
.dm-sgc-sel i.dm-x,.dm-sgc-lr i.dm-x{background:var(--dm-accent-mark,var(--dm-accent))}
.dm-sgc-sel i{margin-left:calc(var(--dm-s-2) - var(--dm-s-3))}
.dm-sgc-sel .dm-t{flex:0 1 auto;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.dm-sgc-sel .dm-t span,.dm-sgc-sel .dm-t.dm-none{color:var(--dm-muted)}
/* the list: the month's events as rows, a muted date, the event and its time on the right; no lines between them, a quiet
   hover fill that reaches 8px out round the words, and the launch keeps its one accent dot, after its title. The rows share
   one grid (subgrid), so the date column is as wide as the widest date and every title starts 12px after it */
.dm-sgc-ls{display:grid;grid-template-columns:auto minmax(0,1fr) auto;column-gap:var(--dm-s-3);margin:0 -8px}
.dm-sgc-lr{display:grid;grid-column:1/-1;grid-template-columns:subgrid;align-items:center;height:32px;padding:0 8px;border-radius:var(--dm-r-sm);font-size:13px;line-height:18px;text-align:left;color:var(--dm-fg);transition:background-color var(--dm-t-fast) var(--dm-ease)}
@media (hover:hover) and (pointer:fine){.dm-sgc-lr:hover{background:var(--dm-row)}}
.dm-sgc-lr:focus-visible{outline:0;box-shadow:0 0 0 2px var(--dm-focus)}
.dm-sgc-lr>.dm-num:first-child{color:var(--dm-muted)}
.dm-sgc-lr .dm-t{min-width:0;display:flex;align-items:center;gap:var(--dm-s-2);white-space:nowrap}
.dm-sgc-lr .dm-t span{min-width:0;overflow:hidden;text-overflow:ellipsis}
.dm-sgc-lr .dm-tm{flex:none;color:var(--dm-muted)}
.dm-sgc-none{padding:var(--dm-s-3) 0 calc(var(--dm-s-3) - 7px);font-size:13px;color:var(--dm-muted)}
/* Studio (owner, 17, 18 and 21 Nov): the head is an off-white strip under a hairline, the switch Studio's monochrome one, the
   chevrons ghost circles; the rows take Studio's 10px corners under one gliding highlight (hoverGlide), and a day's hover is a
   pill. The picked day is the accent in light and white in dark, as every Studio accent */
:root[data-style="studio"] .dm-sgc.dm-panel,:root [data-style="studio"] .dm-sgc.dm-panel,:root [data-style="studio"].dm-sgc.dm-panel{padding:0 16px 16px}
:root[data-style="studio"] .dm-sgc.dm-panel[data-v="list"],:root [data-style="studio"] .dm-sgc.dm-panel[data-v="list"],:root [data-style="studio"].dm-sgc.dm-panel[data-v="list"]{padding-bottom:calc(16px - 7px)}
:root[data-style="studio"] .dm-sgc-h,:root [data-style="studio"] .dm-sgc-h,:root [data-style="studio"].dm-sgc-h{min-height:calc(28px + 2 * var(--dm-strip-y) + 1px);margin:0 -16px;padding:var(--dm-strip-y) 16px;background:var(--dm-strip);border-bottom:1px solid var(--dm-line);border-radius:var(--dm-r-card) var(--dm-r-card) 0 0}
:root[data-style="studio"] .dm-sgc-mt .dm-ib,:root [data-style="studio"] .dm-sgc-mt .dm-ib,:root [data-style="studio"].dm-sgc-mt .dm-ib{border-radius:50%}
:root[data-style="studio"] :is(.dm-sgc-lr>.dm-num,.dm-sgc-sel .dm-num,.dm-sgc-lr .dm-tm),:root [data-style="studio"] :is(.dm-sgc-lr>.dm-num,.dm-sgc-sel .dm-num,.dm-sgc-lr .dm-tm),:root [data-style="studio"]:is(.dm-sgc-lr>.dm-num,.dm-sgc-sel .dm-num,.dm-sgc-lr .dm-tm){font-variant-numeric:tabular-nums}
:root[data-style="studio"] .dm-sgc-lr,:root [data-style="studio"] .dm-sgc-lr,:root [data-style="studio"].dm-sgc-lr{border-radius:10px}
:root[data-style="studio"] .dm-sgc-mo .dm-d b,:root [data-style="studio"] .dm-sgc-mo .dm-d b,:root [data-style="studio"].dm-sgc-mo .dm-d b{border-radius:var(--dm-r-pill)}
SegmentedControl.astroAstro · 28 lines
---
// Generated from designme.dev by scripts/sync.mjs. Edit the site, then sync.
// Segmented control: Switch between views of the same thing, with a sliding indicator.
// The markup, CSS and script are designme.dev's own, run by the shared core in ../core, which mounts the component when it scrolls
// into view and plays its demo. To show your own data, change segmented-control.js. The markup is kept exactly as it is (is:raw).
import type { HTMLAttributes } from 'astro/types';
import '../core/designme.css';
import './segmented-control.css';

export interface Props extends HTMLAttributes<'div'> {
  /** "soft" or "studio" draws it in that style. Leave it out for Blueprint, or for the style set on <html> (data-style="soft" or "studio") */
  'data-style'?: 'soft' | 'studio';
}
const { class: className, ...rest } = Astro.props;
---
<div class:list={['card', className]} data-c="segmented-control" {...rest}>
  <div class="stage-in"><Fragment is:raw>
<div class="sgc panel">
  <div class="sgc-h"><div class="sgc-mt"><button class="ib sgc-pv" aria-label="Previous month" data-tip="Previous month"><svg class="i xs"><use href="#i-chev-l"/></svg></button><b class="sgc-r" aria-live="polite">October 2026</b><button class="ib sgc-nx" aria-label="Next month" data-tip="Next month"><svg class="i xs"><use href="#i-chev-r"/></svg></button></div>
    <div class="sgc-seg" role="tablist" aria-label="View"><span class="sgc-k" aria-hidden="true"></span><button role="tab" aria-selected="false" tabindex="-1" data-v="list" aria-label="List" data-tip="List"><svg class="i s"><use href="#i-list"/></svg></button><button role="tab" aria-selected="true" data-v="cal" aria-label="Calendar" data-tip="Calendar"><svg class="i s"><use href="#i-cal"/></svg></button></div></div>
  <div class="sgc-p" role="tabpanel" tabindex="0"><div class="sgc-in"></div></div>
</div>
  </Fragment></div>
</div>
<script>
  import './segmented-control.js';
</script>
segmented-control.htmlHTML · 10 lines
<div class="card" data-c="segmented-control">
  <div class="stage-in">
    <div class="sgc panel">
      <div class="sgc-h"><div class="sgc-mt"><button class="ib sgc-pv" aria-label="Previous month" data-tip="Previous month"><svg class="i xs"><use href="#i-chev-l"/></svg></button><b class="sgc-r" aria-live="polite">October 2026</b><button class="ib sgc-nx" aria-label="Next month" data-tip="Next month"><svg class="i xs"><use href="#i-chev-r"/></svg></button></div>
        <div class="sgc-seg" role="tablist" aria-label="View"><span class="sgc-k" aria-hidden="true"></span><button role="tab" aria-selected="false" tabindex="-1" data-v="list" aria-label="List" data-tip="List"><svg class="i s"><use href="#i-list"/></svg></button><button role="tab" aria-selected="true" data-v="cal" aria-label="Calendar" data-tip="Calendar"><svg class="i s"><use href="#i-cal"/></svg></button></div></div>
      <div class="sgc-p" role="tabpanel" tabindex="0"><div class="sgc-in"></div></div>
    </div>
  </div>
</div>
segmented-control.cssHTML · 86 lines
/* ---------- Segmented control ---------- */
/* one choice from a few views of the same thing: the picked one sits on a white knob that slides to it. It is a tab
   list, so the arrow keys move along it and the panel under it changes with it. The demo (owner, 28 Nov) is a month of a
   pricing launch: a one-line head, the month as the title between two quiet chevrons on the left and the switch on the right,
   two icons on the grey track (List and Calendar, each named and with a tooltip) */
.sgc{width:100%;max-width:400px;margin:0 auto;padding:var(--dm-s-4);display:flex;flex-direction:column;gap:14px;transition:padding-bottom var(--dm-t) cubic-bezier(.23,1,.32,1)}
/* in the list, the last row's hover room makes up the foot, so its words still end 16px from the card's bottom */
.sgc.panel[data-v="list"]{padding-bottom:calc(var(--dm-s-4) - 7px)}
.sgc-h{display:flex;align-items:center;justify-content:space-between;gap:var(--dm-s-3)}
/* the first chevron's glyph sits on the content's left edge, its 28px hover circle reaching out round it (the 12px glyph is
   centred in the box, so the box starts 8px further out) */
.sgc-mt{display:flex;align-items:center;gap:2px;min-width:0}
.sgc-mt .ib{width:28px;height:28px;color:var(--dm-fg2)}
.sgc-mt .sgc-pv{margin-left:calc((12px - 28px) / 2)}
.sgc-mt b{font-size:14px;font-weight:500;padding:0 var(--dm-s-1);white-space:nowrap}
.sgc-seg{position:relative;display:inline-flex;padding:3px;border-radius:var(--dm-r-pill);background:var(--dm-chip);flex:none}
.sgc-k{position:absolute;top:3px;bottom:3px;left:3px;width:0;border-radius:var(--dm-r-pill);background:var(--dm-raised);box-shadow:var(--dm-seg-k-shadow,var(--dm-shadow));transition:left .42s var(--dm-ease),width .42s var(--dm-ease)}
.sgc-seg button{position:relative;z-index:1;height:30px;padding:0 14px;border-radius:var(--dm-r-pill);font-size:13px;color:var(--dm-fg2);outline:0;transition:color .2s}
.sgc-seg button:has(>.i:only-child){width:36px;padding:0;display:grid;place-items:center}
.sgc-seg button[aria-selected="true"],.sgc-seg button[aria-checked="true"]{color:var(--dm-fg)}
@media (hover:hover) and (pointer:fine){.sgc-seg button:hover{color:var(--dm-fg)}}
.sgc-seg button:focus-visible{box-shadow:0 0 0 2px var(--dm-focus)}
/* the panel is as tall as the view on show, and eases to the next one's height (grow()) */
.sgc-p{position:relative;border-radius:var(--dm-r-in);outline:0}
.sgc-p.growing{overflow-clip-margin:10px}
.sgc-p:focus-visible{box-shadow:0 0 0 2px var(--dm-focus)}
/* a new view crossfades over the one it replaces, so the panel is never empty between them; its days or rows come in one after
   another (mxIn), on Studio's ease in every style. With reduced motion it only swaps */
.sgc-in{--dm-ease:cubic-bezier(.23,1,.32,1)}
.sgc-in.fresh{animation:sgcin .22s var(--dm-ease) both}
.sgc-in.gone{position:absolute;inset:0 0 auto;pointer-events:none;animation:sgcout .22s var(--dm-ease) both}
@keyframes sgcin{from{opacity:0}}
@keyframes sgcout{to{opacity:0}}
@media (prefers-reduced-motion:reduce){.sgc-in.fresh,.sgc-in.gone{animation:none}}
/* nothing in it grows or shrinks when it is pressed (owner, 18 Nov) */
.sgc :is(.ib,.pill):active,:root[data-style="studio"] .sgc .ib:active,:root [data-style="studio"] .sgc .ib:active,:root [data-style="studio"].sgc .ib:active{transform:none}
/* the calendar: a calm month. A grey dot only on a day with something on, the launch day's dot the one accent mark; today a
   quiet grey ring; the picked day a small accent circle. Under a hairline, the picked day's line: its date, its event and time */
.sgc-cal{display:flex;flex-direction:column;gap:14px}
/* the days' circles are centred in their columns, and the grid reaches out into the padding just far enough that Monday's
   circle starts and Sunday's ends on the content's edges, under the head's chevron and switch, at every width: with 7 columns
   of 26px circles and 6 gaps of 4px, each side reaches out by (circles + gaps - width) / 12 */
.sgc-mo{display:grid;grid-template-columns:repeat(7,1fr);gap:2px var(--dm-s-1);margin-inline:calc((7 * 26px + 6 * var(--dm-s-1) - 100%) / 12);font-size:12px;text-align:center}
.sgc-mo .w{font-size:11px;color:var(--dm-muted);padding-bottom:2px}
.sgc-mo .d{position:relative;height:32px;display:grid;place-items:center;color:var(--dm-fg2)}
.sgc-mo .d b{display:grid;place-items:center;width:26px;height:26px;border-radius:50%;font-weight:400;transition:background-color var(--dm-t-fast) var(--dm-ease),color var(--dm-t-fast) var(--dm-ease),box-shadow var(--dm-t-fast) var(--dm-ease)}
@media (hover:hover) and (pointer:fine){.sgc-mo .d:not(.on):hover b{background:var(--dm-row)}}
.sgc-mo .d:focus-visible{outline:0}
.sgc-mo .d:focus-visible b{box-shadow:0 0 0 2px var(--dm-focus)}
.sgc-mo .d.e::after{content:"";position:absolute;bottom:0;left:50%;width:4px;height:4px;margin-left:-2px;border-radius:50%;background:var(--dm-faint)}
.sgc-mo .d.x::after{background:var(--dm-accent-mark,var(--dm-accent))}
.sgc-mo .d.now b{color:var(--dm-fg);box-shadow:inset 0 0 0 1px color-mix(in srgb,var(--dm-line-strong) 50%,transparent)}
.sgc-mo .d.on b{background:var(--dm-accent);color:var(--dm-on-accent);font-weight:500;box-shadow:none}
.sgc-mo .d.on::after{opacity:0}
/* the date, then the event 12px after it; the launch's accent dot follows the line's words, so no line keeps room for a dot
   it doesn't have */
.sgc-sel{display:flex;align-items:center;gap:var(--dm-s-3);padding-top:var(--dm-s-3);border-top:1px solid color-mix(in srgb,var(--dm-line) 50%,transparent);font-size:13px;line-height:18px}
.sgc-sel .num{flex:none;color:var(--dm-muted)}
.sgc-sel i,.sgc-lr i{width:6px;height:6px;border-radius:50%;flex:none}
.sgc-sel i.x,.sgc-lr i.x{background:var(--dm-accent-mark,var(--dm-accent))}
.sgc-sel i{margin-left:calc(var(--dm-s-2) - var(--dm-s-3))}
.sgc-sel .t{flex:0 1 auto;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.sgc-sel .t span,.sgc-sel .t.none{color:var(--dm-muted)}
/* the list: the month's events as rows, a muted date, the event and its time on the right; no lines between them, a quiet
   hover fill that reaches 8px out round the words, and the launch keeps its one accent dot, after its title. The rows share
   one grid (subgrid), so the date column is as wide as the widest date and every title starts 12px after it */
.sgc-ls{display:grid;grid-template-columns:auto minmax(0,1fr) auto;column-gap:var(--dm-s-3);margin:0 -8px}
.sgc-lr{display:grid;grid-column:1/-1;grid-template-columns:subgrid;align-items:center;height:32px;padding:0 8px;border-radius:var(--dm-r-sm);font-size:13px;line-height:18px;text-align:left;color:var(--dm-fg);transition:background-color var(--dm-t-fast) var(--dm-ease)}
@media (hover:hover) and (pointer:fine){.sgc-lr:hover{background:var(--dm-row)}}
.sgc-lr:focus-visible{outline:0;box-shadow:0 0 0 2px var(--dm-focus)}
.sgc-lr>.num:first-child{color:var(--dm-muted)}
.sgc-lr .t{min-width:0;display:flex;align-items:center;gap:var(--dm-s-2);white-space:nowrap}
.sgc-lr .t span{min-width:0;overflow:hidden;text-overflow:ellipsis}
.sgc-lr .tm{flex:none;color:var(--dm-muted)}
.sgc-none{padding:var(--dm-s-3) 0 calc(var(--dm-s-3) - 7px);font-size:13px;color:var(--dm-muted)}
/* Studio (owner, 17, 18 and 21 Nov): the head is an off-white strip under a hairline, the switch Studio's monochrome one, the
   chevrons ghost circles; the rows take Studio's 10px corners under one gliding highlight (hoverGlide), and a day's hover is a
   pill. The picked day is the accent in light and white in dark, as every Studio accent */
:root[data-style="studio"] .sgc.panel,:root [data-style="studio"] .sgc.panel,:root [data-style="studio"].sgc.panel{padding:0 16px 16px}
:root[data-style="studio"] .sgc.panel[data-v="list"],:root [data-style="studio"] .sgc.panel[data-v="list"],:root [data-style="studio"].sgc.panel[data-v="list"]{padding-bottom:calc(16px - 7px)}
:root[data-style="studio"] .sgc-h,:root [data-style="studio"] .sgc-h,:root [data-style="studio"].sgc-h{min-height:calc(28px + 2 * var(--dm-strip-y) + 1px);margin:0 -16px;padding:var(--dm-strip-y) 16px;background:var(--dm-strip);border-bottom:1px solid var(--dm-line);border-radius:var(--dm-r-card) var(--dm-r-card) 0 0}
:root[data-style="studio"] .sgc-mt .ib,:root [data-style="studio"] .sgc-mt .ib,:root [data-style="studio"].sgc-mt .ib{border-radius:50%}
:root[data-style="studio"] :is(.sgc-lr>.num,.sgc-sel .num,.sgc-lr .tm),:root [data-style="studio"] :is(.sgc-lr>.num,.sgc-sel .num,.sgc-lr .tm),:root [data-style="studio"]:is(.sgc-lr>.num,.sgc-sel .num,.sgc-lr .tm){font-variant-numeric:tabular-nums}
:root[data-style="studio"] .sgc-lr,:root [data-style="studio"] .sgc-lr,:root [data-style="studio"].sgc-lr{border-radius:10px}
:root[data-style="studio"] .sgc-mo .d b,:root [data-style="studio"] .sgc-mo .d b,:root [data-style="studio"].sgc-mo .d b{border-radius:var(--dm-r-pill)}
segmented-control.jsHTML · 71 lines
DM.def('segmented-control', (r, c) => {
  r.innerHTML = r.innerHTML.replace('{chev-l}', I('chev-l','xs')).replace('{chev-r}', I('chev-r','xs')).replace('{list}', I('list','s')).replace('{cal}', I('cal','s'));
  const uid = Math.random().toString(36).slice(2, 7);
  const seg = $('.sgc-seg', r), knob = $('.sgc-k', r), tabs = $$('[role="tab"]', seg), panel = $('.sgc-p', r), title = $('.sgc-r', r), root = $('.sgc', r) || r;
  root.dataset.v = 'cal';
  // Studio's one hover: a highlight that glides from row to row in the list (a day's hover is its own circle)
  c.offs.push(hoverGlide(panel, '.sgc-lr'));
  let inner = $('.sgc-in', r);
  tabs.forEach(t => { t.id = `sgc-${t.dataset.v}-${uid}`; t.setAttribute('aria-controls', 'sgc-p-' + uid); });
  panel.id = 'sgc-p-' + uid;
  // a pricing launch in October 2026: today is Friday the 23rd, and the launch on the 28th is the one accent mark
  const TODAY = new Date(2026, 9, 23, 12);
  const EV = [['2026-10-06', 'Kickoff', '10:00'], ['2026-10-09', 'Brief review', '14:00'], ['2026-10-14', 'Copy review', '11:00'], ['2026-10-20', 'Design sign-off', '16:00'], ['2026-10-26', 'QA pass', '09:30'], ['2026-10-28', 'Pricing goes live', '10:00', 1]];
  const iso = d => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
  const day = k => { const [y, m, d] = k.split('-').map(Number); return new Date(y, m - 1, d, 12); };
  const fmt = (d, o) => d.toLocaleDateString('en-US', o), short = d => fmt(d, { month:'short', day:'numeric' });
  const ev = k => EV.find(e => e[0] === k);
  let cur = 'cal', month = new Date(2026, 9, 1, 12), sel = day('2026-10-28');
  // a month's picked day when you step to it: the launch, else its first event, else the 1st
  const firstPick = m => { const L = EV.filter(e => e[0].startsWith(iso(m).slice(0, 7))); return day((L.find(e => e[3]) || L[0] || [iso(m)])[0]); };
  const selLine = () => { const e = ev(iso(sel)); return `<span class="num">${short(sel)}</span>` + (e ? `<span class="t">${e[1]} <span>· ${e[2]}</span></span>${e[3] ? '<i class="x"></i>' : ''}` : '<span class="t none">Nothing planned</span>'); };
  const V = {
    cal:() => { const a = month, lead = (a.getDay() + 6) % 7, len = new Date(a.getFullYear(), a.getMonth() + 1, 0).getDate();
      return `<div class="sgc-cal"><div class="sgc-mo">${['M','T','W','T','F','S','S'].map(w => `<span class="w" aria-hidden="true">${w}</span>`).join('')}${'<span></span>'.repeat(lead)}${Array.from({ length:len }, (_, i) => { const x = new Date(a.getFullYear(), a.getMonth(), i + 1, 12), k = iso(x), e = ev(k), on = k === iso(sel);
        return `<button class="d num${e ? ' e' : ''}${e && e[3] ? ' x' : ''}${k === iso(TODAY) ? ' now' : ''}${on ? ' on' : ''}" data-d="${k}" aria-pressed="${on}" aria-label="${fmt(x, { weekday:'long', month:'long', day:'numeric' })}, ${e ? e[1] : 'nothing planned'}"><b>${i + 1}</b></button>`; }).join('')}</div><div class="sgc-sel" aria-live="polite">${selLine()}</div></div>`; },
    list:() => { const L = EV.filter(e => e[0].startsWith(iso(month).slice(0, 7)));
      return L.length ? `<div class="sgc-ls">${L.map(e => `<button class="sgc-lr" data-d="${e[0]}"><span class="num">${short(day(e[0]))}</span><span class="t"><span>${e[1]}</span>${e[3] ? '<i class="x"></i>' : ''}</span><span class="num tm">${e[2]}</span></button>`).join('')}</div>` : '<div class="sgc-none">Nothing planned this month</div>'; }
  };
  // the knob slides to the picked tab and takes its width
  const place = () => { const t = tabs.find(x => x.getAttribute('aria-selected') === 'true'); knob.style.left = t.offsetLeft + 'px'; knob.style.width = t.offsetWidth + 'px'; };
  // picking a day moves the small accent circle to it and the line under the hairline changes to it; a row in the list opens
  // its day in the calendar
  const choose = k => { sel = day(k); $$('.sgc-mo .d', inner).forEach(b => { const on = b.dataset.d === k; b.classList.toggle('on', on); b.setAttribute('aria-pressed', on); }); const l = $('.sgc-sel', inner); if (l) swap(l, selLine(), true); };
  const bind = el => { $$('.sgc-mo .d', el).forEach(b => b.onclick = () => choose(b.dataset.d)); $$('.sgc-lr', el).forEach(b => b.onclick = () => { sel = day(b.dataset.d); pick(tabs[1]); }); };
  // shows the view: the new one crossfades in over the old, which stays until it has faded, so no frame is empty; its days or
  // rows come in one after another, and the panel eases to the new view's height (grow())
  function show(){
    const old = inner; inner = html(`<div class="sgc-in fresh">${V[cur]()}</div>`); bind(inner);
    $$('.sgc-in.gone', panel).forEach(x => x.remove());
    old.classList.remove('fresh'); old.classList.add('gone'); old.inert = true; old.setAttribute('aria-hidden', 'true');
    old.parentElement.appendChild(inner);
    c.later(REDUCE ? 0 : 240, () => old.remove());
    if (!REDUCE){ const days = $$('.sgc-mo .d', inner); if (days.length) mxIn([...days, $('.sgc-sel', inner)], { ms:300, step:6, y:4, blur:0 }); else mxIn($$('.sgc-lr', inner), { ms:300, step:40, y:4, blur:0 }); }
  }
  function pick(t, focus){
    tabs.forEach(x => { const on = x === t; x.setAttribute('aria-selected', on); x.tabIndex = on ? 0 : -1; });
    panel.setAttribute('aria-labelledby', t.id); place(); hideTip();
    if (focus) t.focus({ preventScroll:true });
    if (t.dataset.v === cur) return; cur = t.dataset.v; root.dataset.v = cur; show();
  }
  // previous and next step a month; the title eases over to the new one
  const step = k => { month = new Date(month.getFullYear(), month.getMonth() + k, 1, 12); sel = firstPick(month); swap(title, fmt(month, { month:'long', year:'numeric' })); show(); };
  $('.sgc-pv', r).onclick = () => step(-1); $('.sgc-nx', r).onclick = () => step(1);
  tabs.forEach(t => t.onclick = () => pick(t));
  // the arrow keys move along the tabs and pick as they go; Home and End jump to the ends
  seg.onkeydown = e => {
    const i = tabs.indexOf(document.activeElement); if (i < 0) return;
    const go = { ArrowRight:i + 1, ArrowLeft:i - 1, Home:0, End:tabs.length - 1 }[e.key]; if (go === undefined) return;
    e.preventDefault(); pick(tabs[(go + tabs.length) % tabs.length], true);
  };
  inner.innerHTML = V.cal(); bind(inner); pick(tabs[1]); c.offs.push(grow(panel));
  knob.style.transition = 'none'; requestAnimationFrame(() => { place(); requestAnimationFrame(() => { knob.style.transition = ''; }); });
  const ro = new ResizeObserver(place); ro.observe(seg); c.offs.push(() => ro.disconnect());
  // the preview's story, on a calm loop: the calendar, the list, and back to the calendar
  c.story(async s => {
    await s.beat(4);
    await s.tap(tabs[0]); s.away(); await s.beat(5);
    await s.tap(tabs[1]); s.away(); await s.beat(5);
  });
});
06

Questions

What people ask about it.

Should it be tabs or a radio group?
Tabs when it changes what a panel shows, like a calendar view. A radio group when it sets a value that's saved or sent, like a billing period.
Can an option be only an icon?
Yes. Put the icon in label and the option's name in title: the button takes it as its aria-label and shows it in a tooltip, as the demo's List and Calendar do.
Does the knob slide when the labels change width?
Yes. It measures the picked option whenever the control resizes, so it follows a translated label or a new font.
How many options can it take?
It works best with two to five short ones. Past that, the options get narrow on a phone.
07

More in Dates

Pickers for single dates and date ranges.

Date pickerA field that opens a calendar, with quick picks and natural language.
Event calendarA week view where the agent finds a free slot for you.
Meeting cardThe next meeting from countdown to wrap-up, with the time already gone hatched out and a join that stays open.