Skip to content

Tabs

A flexible tabs component for organizing content into switchable panels. Keyboard accessible, animation-ready, and available in six visual styles.

Features

  • 🎨 6 Variants: solid, flat, bordered, ghost, glass, frost
  • 🌈 7 Colors: primary, secondary, info, success, warning, error (+ neutral default)
  • 📏 3 Sizes: sm, md, lg
  • Accessible: Full ARIA roles (tablist, tab, tabpanel), keyboard navigation
  • 🔀 Panel Transitions: Fade + slide-up animation on panel reveal
  • 🧩 Composable: Three separate elements — bit-tabs, bit-tab-item, bit-tab-panel

Source Code

View Source Code (bit-tabs)
ts
import {
  computed,
  createContext,
  defineComponent,
  handle,
  html,
  onMount,
  provide,
  type ReadonlySignal,
  ref,
  signal,
  watch,
} from '@vielzeug/craftit';

import type { ComponentSize, ThemeColor, VisualVariant } from '../../types';

import { colorThemeMixin } from '../../styles';

/** Context provided by bit-tabs to its bit-tab-item and bit-tab-panel children. */
export type TabsContext = {
  color: ReadonlySignal<ThemeColor | undefined>;
  orientation: ReadonlySignal<'horizontal' | 'vertical'>;
  size: ReadonlySignal<ComponentSize | undefined>;
  value: ReadonlySignal<string | undefined>;
  variant: ReadonlySignal<VisualVariant | undefined>;
};
/** Injection key for the tabs context. */
export const TABS_CTX = createContext<TabsContext>('TabsContext');

import styles from './tabs.css?inline';

export type BitTabsEvents = {
  change: { value: string };
};

export type BitTabsProps = {
  /**
   * Keyboard activation mode.
   * - `'auto'` (default): Selecting a tab on arrow-key focus immediately activates it (ARIA recommendation for most cases).
   * - `'manual'`: Arrow keys only move focus; the user must press Enter or Space to activate the focused tab.
   */
  activation?: 'auto' | 'manual';
  /** Theme color */
  color?: ThemeColor;
  /** Accessible label for the tablist (passed as aria-label). Use when there is no visible heading labelling the tabs. */
  label?: string;
  /** Tab list orientation */
  orientation?: 'horizontal' | 'vertical';
  /** Component size */
  size?: ComponentSize;
  /** Currently selected tab value */
  value?: string;
  /** Visual style variant */
  variant?: VisualVariant;
};

/**
 * Tabs container. Manages tab selection and syncs state to child tab items and panels.
 *
 * @element bit-tabs
 *
 * @attr {string} value - The value of the currently selected tab
 * @attr {string} variant - Visual variant: 'solid' | 'flat' | 'bordered' | 'ghost' | 'glass' | 'frost'
 * @attr {string} size - Size: 'sm' | 'md' | 'lg'
 * @attr {string} color - Theme color: 'primary' | 'secondary' | 'info' | 'success' | 'warning' | 'error'
 *
 * @fires change - Emitted when the active tab changes, detail: { value: string }
 *
 * @slot tabs - Place `bit-tab-item` elements here
 * @slot - Place `bit-tab-panel` elements here
 *
 * @example
 * ```html
 * <bit-tabs value="tab1" variant="underline">
 *   <bit-tab-item slot="tabs" value="tab1">Overview</bit-tab-item>
 *   <bit-tab-item slot="tabs" value="tab2">Settings</bit-tab-item>
 *   <bit-tab-panel value="tab1"><p>Overview content</p></bit-tab-panel>
 *   <bit-tab-panel value="tab2"><p>Settings content</p></bit-tab-panel>
 * </bit-tabs>
 * ```
 */
export const TABS_TAG = defineComponent<BitTabsProps, BitTabsEvents>({
  props: {
    activation: { default: 'auto' },
    color: { default: undefined },
    label: { default: undefined },
    orientation: { default: 'horizontal' },
    size: { default: undefined },
    value: { default: undefined },
    variant: { default: undefined },
  },
  setup({ emit, host, props }) {
    const tablistRef = ref<HTMLElement>();
    const indicatorRef = ref<HTMLElement>();
    const selectedValue = signal<string | undefined>(props.value.value);
    const getTabs = () => [...host.querySelectorAll<HTMLElement>('bit-tab-item')];

    const setSelection = (value: string | undefined, shouldEmit = false) => {
      selectedValue.value = value;

      if (value == null) host.removeAttribute('value');
      else if (host.getAttribute('value') !== value) host.setAttribute('value', value);

      if (shouldEmit && value) emit('change', { value });
    };

    const ensureSelection = () => {
      const tabs = getTabs();

      // During initial connection, slotted tab items may not be assigned yet.
      // Keep current selection until tabs exist instead of falling back to undefined.
      if (tabs.length === 0) return;

      const current = selectedValue.value;
      const hasCurrent = current
        ? tabs.some((tab) => tab.getAttribute('value') === current && !tab.hasAttribute('disabled'))
        : false;

      if (hasCurrent) return;

      const firstEnabled = tabs.find((tab) => !tab.hasAttribute('disabled'))?.getAttribute('value') ?? undefined;

      setSelection(firstEnabled, false);
    };

    watch(props.value, (value) => {
      selectedValue.value = value;
      ensureSelection();
    });

    provide(TABS_CTX, {
      color: props.color,
      orientation: computed(() => props.orientation.value ?? 'horizontal'),
      size: props.size,
      value: selectedValue,
      variant: props.variant,
    });

    const moveIndicator = (activeTab: HTMLElement | undefined) => {
      const indicator = indicatorRef.value;
      const tablist = tablistRef.value;

      if (!indicator || !tablist || !activeTab) return;

      if (props.orientation.value === 'vertical') {
        const tabRect = activeTab.getBoundingClientRect();
        const listRect = tablist.getBoundingClientRect();

        indicator.style.top = `${tabRect.top - listRect.top + tablist.scrollTop}px`;
        indicator.style.height = `${tabRect.height}px`;
        indicator.style.left = '0';
        indicator.style.width = '';
      } else {
        const tabRect = activeTab.getBoundingClientRect();
        const listRect = tablist.getBoundingClientRect();

        indicator.style.left = `${tabRect.left - listRect.left + tablist.scrollLeft}px`;
        indicator.style.width = `${tabRect.width}px`;
        indicator.style.top = '';
        indicator.style.height = '';
      }
    };
    const triggerIndicator = () => {
      const value = selectedValue.value;

      if (!value) return;

      const activeTab = getTabs().find((t) => t.getAttribute('value') === value);

      moveIndicator(activeTab);
    };

    watch(selectedValue, () => requestAnimationFrame(triggerIndicator));

    const handleTabClick = (e: Event) => {
      const tab = (e.target as HTMLElement).closest('bit-tab-item') as HTMLElement | null;

      if (!tab || tab.hasAttribute('disabled')) return;

      // Guard: only respond to tab-items that belong to THIS tabs instance, not nested ones.
      if (tab.closest('bit-tabs') !== host) return;

      const value = tab.getAttribute('value');

      if (!value || value === selectedValue.value) return;

      setSelection(value, true);
    };
    const handleKeydown = (e: KeyboardEvent) => {
      const tabs = getTabs().filter((t) => !t.hasAttribute('disabled'));
      const current = tabs.findIndex((t) => t.getAttribute('value') === selectedValue.value);
      const isVertical = props.orientation.value === 'vertical';
      // eslint-disable-next-line no-useless-assignment
      let next = current;

      if (e.key === (isVertical ? 'ArrowDown' : 'ArrowRight')) next = (current + 1) % tabs.length;
      else if (e.key === (isVertical ? 'ArrowUp' : 'ArrowLeft')) next = (current - 1 + tabs.length) % tabs.length;
      else if (!isVertical && e.key === 'ArrowDown') next = (current + 1) % tabs.length;
      else if (!isVertical && e.key === 'ArrowUp') next = (current - 1 + tabs.length) % tabs.length;
      else if (e.key === 'Home') next = 0;
      else if (e.key === 'End') next = tabs.length - 1;
      else if (props.activation.value === 'manual' && (e.key === 'Enter' || e.key === ' ')) {
        // Manual mode: activate the currently focused tab
        const focused = tabs.find(
          (t) => t === document.activeElement || t.shadowRoot?.activeElement === document.activeElement,
        );
        const focusedValue = focused?.getAttribute('value');

        if (focusedValue && focusedValue !== selectedValue.value) {
          setSelection(focusedValue, true);
        }

        return;
      } else return;

      e.preventDefault();

      const value = tabs[next]?.getAttribute('value');

      if (value) {
        (tabs[next] as HTMLElement)?.focus();

        if (props.activation.value !== 'manual') {
          // Auto mode: activate on focus
          setSelection(value, true);
        }
      }
    };

    handle(host, 'click', handleTabClick);
    handle(host, 'keydown', handleKeydown);
    onMount(() => {
      const syncSelection = () => {
        ensureSelection();
        triggerIndicator();
      };
      const tabsSlot = host.shadowRoot?.querySelector<HTMLSlotElement>('slot[name="tabs"]');

      if (tabsSlot) {
        tabsSlot.addEventListener('slotchange', syncSelection);
      }

      syncSelection();
      requestAnimationFrame(syncSelection);

      return () => {
        if (tabsSlot) {
          tabsSlot.removeEventListener('slotchange', syncSelection);
        }
      };
    });

    return html`
      <div class="tablist-wrapper">
        <div
          role="tablist"
          ref=${tablistRef}
          part="tablist"
          :aria-orientation="${() => props.orientation.value}"
          :aria-label="${() => props.label.value ?? null}">
          <slot name="tabs"></slot>
        </div>
        <div class="indicator" ref=${indicatorRef} part="indicator"></div>
      </div>
      <div class="panels" part="panels">
        <slot></slot>
      </div>
    `;
  },
  styles: [colorThemeMixin, styles],
  tag: 'bit-tabs',
});
View Source Code (bit-tab-item)
ts
import { computed, defineComponent, effect, fire, html, typed, inject, syncContextProps } from '@vielzeug/craftit';

import type { ComponentSize, ThemeColor, VisualVariant } from '../../types';

import { coarsePointerMixin, colorThemeMixin, forcedColorsFocusMixin } from '../../styles';
import { TABS_CTX } from '../tabs/tabs';
import styles from './tab-item.css?inline';

export type BitTabItemProps = {
  /** Whether this tab is currently selected (set by bit-tabs) */
  active?: boolean;
  /** Theme color (inherited from bit-tabs) */
  color?: ThemeColor;
  /** Disable this tab */
  disabled?: boolean;
  /** Size (inherited from bit-tabs) */
  size?: ComponentSize;
  /** Unique value identifier — must match a bit-tab-panel value */
  value: string;
  /** Visual variant (inherited from bit-tabs) */
  variant?: VisualVariant;
};

/**
 * Individual tab trigger. Must be placed in the `tabs` slot of `bit-tabs`.
 *
 * @element bit-tab-item
 *
 * @attr {string} value - Unique identifier, matches the corresponding bit-tab-panel value
 * @attr {boolean} active - Set by the parent bit-tabs when this tab is selected
 * @attr {boolean} disabled - Prevents selection
 * @attr {string} size - 'sm' | 'md' | 'lg'
 * @attr {string} variant - Inherited from bit-tabs
 * @attr {string} color - Inherited from bit-tabs: 'primary' | 'secondary' | 'info' | 'success' | 'warning' | 'error'
 *
 * @slot prefix - Icon or content before the label
 * @slot - Tab label
 * @slot suffix - Badge or count after the label
 *
 * @example
 * ```html
 * <bit-tab-item slot="tabs" value="overview">Overview</bit-tab-item>
 * <bit-tab-item slot="tabs" value="settings" disabled>Settings</bit-tab-item>
 * ```
 */
export const TAB_ITEM_TAG = defineComponent<BitTabItemProps>({
  props: {
    active: typed<boolean>(false),
    color: typed<BitTabItemProps['color']>(undefined),
    disabled: typed<boolean>(false),
    size: typed<BitTabItemProps['size']>(undefined),
    value: typed<string>(''),
    variant: typed<BitTabItemProps['variant']>(undefined),
  },
  setup({ host, props }) {
    const tabsCtx = inject(TABS_CTX, undefined);

    syncContextProps(tabsCtx, props, ['color', 'size', 'variant']);

    const isActive = tabsCtx
      ? computed(() => !!tabsCtx.value.value && tabsCtx.value.value === props.value.value)
      : props.active;

    effect(() => {
      host.toggleAttribute('active', isActive.value);
    });

    const ariaSelected = computed(() => String(isActive.value));
    const tabIndex = computed(() => (isActive.value ? '0' : '-1'));
    const handleClick = () => {
      if (props.disabled.value) return;

      fire.custom(host, 'click', {
        detail: { value: props.value.value },
      });
    };

    return html`
      <button
        role="tab"
        type="button"
        part="tab"
        :id="${() => `tab-${props.value.value}`}"
        :aria-selected=${ariaSelected}
        :tabindex=${tabIndex}
        :aria-disabled=${computed(() => String(props.disabled.value))}
        :aria-controls="${() => `tabpanel-${props.value.value}`}"
        @click=${handleClick}>
        <slot name="prefix"></slot>
        <slot></slot>
        <slot name="suffix"></slot>
      </button>
    `;
  },
  styles: [colorThemeMixin, forcedColorsFocusMixin('button'), coarsePointerMixin, styles],
  tag: 'bit-tab-item',
});
View Source Code (bit-tab-panel)
ts
import { computed, defineComponent, effect, html, typed, inject, signal } from '@vielzeug/craftit';

import { reducedMotionMixin } from '../../styles';
import { TABS_CTX } from '../tabs/tabs';
import styles from './tab-panel.css?inline';

export type BitTabPanelProps = {
  /** Active state (managed by bit-tabs) */
  active?: boolean;
  /** When true, the panel content is not rendered until first activation (preserves resources) */
  lazy?: boolean;
  /** Panel padding size: 'none' | 'xs' | 'sm' | 'md' | 'lg' | 'xl' | '2xl' (default: 'md' = var(--size-4)) */
  padding?: 'none' | 'xs' | 'sm' | 'md' | 'lg' | 'xl' | '2xl';
  /** Must match the `value` of its corresponding bit-tab-item */
  value: string;
};

/**
 * Content panel for a tab. Shown when its `value` matches the selected tab.
 *
 * @element bit-tab-panel
 *
 * @attr {string} value - Must match the corresponding bit-tab-item value
 * @attr {boolean} active - Toggled by the parent bit-tabs
 * @attr {string} padding - Panel padding: 'none' | 'xs' | 'sm' | 'md' (default) | 'lg' | 'xl' | '2xl'
 *
 * @slot - Panel content
 *
 * @example
 * ```html
 * <bit-tab-panel value="overview"><p>Overview content here</p></bit-tab-panel>
 * <bit-tab-panel value="settings" padding="lg"><p>Large padding</p></bit-tab-panel>
 * <bit-tab-panel value="code" padding="none"><pre>No padding for code</pre></bit-tab-panel>
 * ```
 */
export const TAB_PANEL_TAG = defineComponent<BitTabPanelProps>({
  props: {
    active: typed<boolean>(false),
    lazy: typed<boolean>(false),
    padding: typed<BitTabPanelProps['padding']>('md'),
    value: typed<string>(''),
  },
  setup({ host, props }) {
    const tabsCtx = inject(TABS_CTX, undefined);
    const isActive = tabsCtx
      ? computed(() => !!tabsCtx.value.value && tabsCtx.value.value === props.value.value)
      : props.active;
    // Map padding prop to CSS variable
    const paddingValue = computed(() => {
      const paddingMap: Record<string, string> = {
        '2xl': 'var(--size-12)',
        lg: 'var(--size-6)',
        md: 'var(--size-4)',
        none: '0',
        sm: 'var(--size-2)',
        xl: 'var(--size-8)',
        xs: 'var(--size-1)',
      };
      const key = props.padding.value ?? 'md';

      return paddingMap[key] ?? paddingMap.md;
    });
    // Track whether the panel has ever been active (for lazy rendering)
    const hasBeenActive = signal(false);

    effect(() => {
      host.toggleAttribute('active', isActive.value);

      if (isActive.value) hasBeenActive.value = true;
    });

    // shouldRender: true if not lazy OR has been active at least once
    const shouldRender = computed(() => !props.lazy.value || hasBeenActive.value);

    return html`
      <div
        class="panel"
        part="panel"
        role="tabpanel"
        :id="${() => `tabpanel-${props.value.value}`}"
        :aria-labelledby="${() => `tab-${props.value.value}`}"
        :aria-hidden=${() => String(!isActive.value)}
        :style="${() => `--tab-panel-padding: ${paddingValue.value}`}"
        tabindex="0">
        ${() => (shouldRender.value ? html`<slot></slot>` : '')}
      </div>
    `;
  },
  styles: [reducedMotionMixin, styles],
  tag: 'bit-tab-panel',
});

Basic Usage

html
<bit-tabs value="overview">
  <bit-tab-item slot="tabs" value="overview">Overview</bit-tab-item>
  <bit-tab-item slot="tabs" value="settings">Settings</bit-tab-item>
  <bit-tab-item slot="tabs" value="billing">Billing</bit-tab-item>

  <bit-tab-panel value="overview"><p>Overview content.</p></bit-tab-panel>
  <bit-tab-panel value="settings"><p>Settings content.</p></bit-tab-panel>
  <bit-tab-panel value="billing"><p>Billing content.</p></bit-tab-panel>
</bit-tabs>

<script type="module">
  import '@vielzeug/buildit/tabs';
  import '@vielzeug/buildit/tab-item';
  import '@vielzeug/buildit/tab-panel';
</script>

Visual Options

Variants

Solid (Default)

Pill-style tabs in a rounded container — clean and contained.

PreviewCode
RTL

Flat

Tabs and panel share a single container background — they read as one unified block.

PreviewCode
RTL

Bordered

Tabs that visually connect to their panel with a shared border.

PreviewCode
RTL

Ghost

Open tabs with a filled active pill — no container border, floats freely.

PreviewCode
RTL

Glass & Frost Variants

Translucent tab bars with backdrop blur — best used over rich backgrounds.

Best Used With

Glass and frost variants look best over colorful backgrounds or images to showcase the blur and transparency effects.

PreviewCode
RTL

Colors

Set color on bit-tabs to apply a theme color — it propagates automatically to all tab items. The color drives the active pill fill on ghost, the focus ring on all variants, and the indicator line on future underline-style usage.

PreviewCode
RTL

Sizes

PreviewCode
RTL

Customization

Icons & Badges

Use the prefix and suffix slots on bit-tab-item to add icons or notification badges.

PreviewCode
RTL

States

Lazy Panels

Add lazy to a bit-tab-panel to defer rendering its slot content until the tab is first activated. Once activated, the content stays rendered even if the tab is later switched away. This is useful for panels containing expensive components or data-fetching logic.

html
<bit-tabs value="tab1">
  <bit-tab-item slot="tabs" value="tab1">Quick</bit-tab-item>
  <bit-tab-item slot="tabs" value="tab2">Heavy</bit-tab-item>

  <bit-tab-panel value="tab1"><p>Rendered immediately.</p></bit-tab-panel>
  <bit-tab-panel value="tab2" lazy>
    <!-- Only rendered after the "Heavy" tab is first clicked -->
    <my-heavy-component></my-heavy-component>
  </bit-tab-panel>
</bit-tabs>

Disabled Tabs

Prevent specific tabs from being selected.

PreviewCode
RTL

Keyboard Navigation

KeyAction
ArrowRightMove to the next tab (wraps around)
ArrowLeftMove to the previous tab (wraps around)
HomeJump to the first tab
EndJump to the last tab

Disabled tabs are skipped during keyboard navigation.

API Reference

bit-tabs Attributes

AttributeTypeDefaultDescription
valuestringValue of the currently selected tab
variant'solid' | 'flat' | 'bordered' | 'ghost' | 'glass' | 'frost''solid'Visual style of the tab bar
size'sm' | 'md' | 'lg''md'Size applied to all tab items
color'primary' | 'secondary' | 'info' | 'success' | 'warning' | 'error'Theme color propagated to all tab items

bit-tabs Events

EventDetailDescription
change{ value: string }Fired when the active tab changes

bit-tabs Slots

SlotDescription
tabsPlace bit-tab-item elements here
(default)Place bit-tab-panel elements here

bit-tab-item Attributes

AttributeTypeDefaultDescription
valuestringRequired. Must match the corresponding bit-tab-panel value
activebooleanfalseWhether this tab is selected (managed by bit-tabs)
disabledbooleanfalsePrevents the tab from being selected
size'sm' | 'md' | 'lg'inheritedInherited from parent bit-tabs
variantstringinheritedInherited from parent bit-tabs
color'primary' | 'secondary' | 'info' | 'success' | 'warning' | 'error'inheritedInherited from parent bit-tabs

bit-tab-item Slots

SlotDescription
prefixIcon or content before the label
(default)Tab label text
suffixBadge or count after the label

bit-tab-panel Attributes

AttributeTypeDefaultDescription
valuestringRequired. Must match the corresponding bit-tab-item value
activebooleanfalseWhether this panel is visible (managed by bit-tabs)
lazybooleanfalseDefer rendering slot content until the panel is first activated

CSS Custom Properties

PropertyDefaultDescription
--tabs-transitionvar(--transition-normal)Transition speed for tab hover states
--tabs-radiusvar(--rounded-lg)Border radius of the tab bar container
--tab-panel-paddingvar(--size-4)Padding inside each tab panel

Accessibility

The tabs component follows the WAI-ARIA Tabs Pattern best practices.

bit-tabs

Keyboard Navigation

  • ArrowRight / ArrowLeft navigate between tabs; Home / End jump to first / last.
  • Disabled tabs are skipped during keyboard navigation.

Screen Readers

  • The tab list has role="tablist".
  • Each tab has role="tab" with aria-selected and aria-controls pointing to its panel.
  • Each panel has role="tabpanel" with aria-labelledby pointing to its tab.
  • Disabled tabs have aria-disabled="true".

Best Practices

Do:

  • Keep tab labels short and descriptive (ideally 1–3 words).
  • Always set a default value on bit-tabs so a tab is active on first render.
  • Use the prefix and suffix slots on bit-tab-item to add icons or notification counts.
  • Use variant="bordered" or variant="flat" when tabs need to feel visually connected to the panel content below them.

Don't:

  • Use more than 5–7 tabs — consider a sidebar navigation for larger sets of sections.
  • Use tabs to represent sequential steps; use a stepper component for linear flows.
  • Nest tabs inside tabs — it creates confusing navigation hierarchies.