탐색

v2.1.0
탐색

탭

하나의 가는 선 위에 레이블을 나란히 놓고, 현재 탭에 글자색으로 밑줄을 표시합니다.

이 페이지의 내용

탭 레이블은 하나의 가는 선 위에 나란히 놓이고, 현재 탭에는 글자색으로 밑줄을 표시합니다. 탭은 같은 수준의 페이지나 패널을 전환합니다. 여러 값 중 하나를 고르는 간결한 UI에는 세그먼트 컨트롤을 사용합니다.

브라우저가 CSS 앵커 포지셔닝을 지원하면 aria-selected 값이 바뀔 때 밑줄 하나가 현재 탭으로 부드럽게 이동합니다. 밑줄의 위쪽 모서리는 각이 도드라지지 않도록 부드럽게 처리합니다. 지원하지 않는 브라우저에서는 각 탭이 자체 밑줄을 표시합니다.

탭

<nav class="tabs" aria-label="Project">  <a class="tabs-item" href="#overview" aria-current="page">Overview</a>  <a class="tabs-item" href="#activity">Activity</a>  <a class="tabs-item" href="#settings">Settings</a></nav>
<nav className="tabs" aria-label="Project">  <a className="tabs-item" href="#overview" aria-current="page">Overview</a>  <a className="tabs-item" href="#activity">Activity</a>  <a className="tabs-item" href="#settings">Settings</a></nav>
<nav class="tabs" aria-label="Project">  <a class="tabs-item" href="#overview" aria-current="page">Overview</a>  <a class="tabs-item" href="#activity">Activity</a>  <a class="tabs-item" href="#settings">Settings</a></nav>
<template>  <nav class="tabs" aria-label="Project">    <a class="tabs-item" href="#overview" aria-current="page">Overview</a>    <a class="tabs-item" href="#activity">Activity</a>    <a class="tabs-item" href="#settings">Settings</a>  </nav></template>

#개수 표시

개수 표시

<nav class="tabs" aria-label="Repository">  <a class="tabs-item" href="#code" aria-current="page">Code</a>  <a class="tabs-item" href="#issues">Issues <span class="badge badge-sm badge-pill">24</span></a>  <a class="tabs-item" href="#pulls">    Pull requests <span class="badge badge-sm badge-pill">3</span>  </a></nav>
<nav className="tabs" aria-label="Repository">  <a className="tabs-item" href="#code" aria-current="page">Code</a>  <a className="tabs-item" href="#issues">    Issues <span className="badge badge-sm badge-pill">24</span>  </a>  <a className="tabs-item" href="#pulls">    Pull requests <span className="badge badge-sm badge-pill">3</span>  </a></nav>
<nav class="tabs" aria-label="Repository">  <a class="tabs-item" href="#code" aria-current="page">Code</a>  <a class="tabs-item" href="#issues">Issues <span class="badge badge-sm badge-pill">24</span></a>  <a class="tabs-item" href="#pulls">    Pull requests <span class="badge badge-sm badge-pill">3</span>  </a></nav>
<template>  <nav class="tabs" aria-label="Repository">    <a class="tabs-item" href="#code" aria-current="page">Code</a>    <a class="tabs-item" href="#issues">Issues <span class="badge badge-sm badge-pill">24</span></a>    <a class="tabs-item" href="#pulls">      Pull requests <span class="badge badge-sm badge-pill">3</span>    </a>  </nav></template>

#작은 탭

작은 탭

<nav class="tabs tabs-sm" aria-label="Period">  <a class="tabs-item" href="#day">Day</a>  <a class="tabs-item" href="#week" aria-current="page">Week</a>  <a class="tabs-item" href="#month">Month</a></nav>
<nav className="tabs tabs-sm" aria-label="Period">  <a className="tabs-item" href="#day">Day</a>  <a className="tabs-item" href="#week" aria-current="page">Week</a>  <a className="tabs-item" href="#month">Month</a></nav>
<nav class="tabs tabs-sm" aria-label="Period">  <a class="tabs-item" href="#day">Day</a>  <a class="tabs-item" href="#week" aria-current="page">Week</a>  <a class="tabs-item" href="#month">Month</a></nav>
<template>  <nav class="tabs tabs-sm" aria-label="Period">    <a class="tabs-item" href="#day">Day</a>    <a class="tabs-item" href="#week" aria-current="page">Week</a>    <a class="tabs-item" href="#month">Month</a>  </nav></template>

#탭 패널

페이지 안에서 패널을 전환할 때는 WAI-ARIA 탭 패턴을 따릅니다. role="tablist" 컨테이너에 aria-selected와 aria-controls를 지정한 role="tab" 버튼을 배치하고 role="tabpanel" 영역을 사용합니다. 스타일시트는 모든 상태의 모양을 표시합니다. tabs 동작은 패널을 전환하고 탭 목록의 키보드 조작을 처리합니다.

탭 목록

<div class="tabs" role="tablist" aria-label="Account">  <button type="button" class="tabs-item" role="tab" id="tab-profile" aria-selected="true" aria-controls="panel-profile">    Profile  </button>  <button type="button" class="tabs-item" role="tab" id="tab-billing" aria-selected="false" aria-controls="panel-billing" tabindex="-1">    Billing  </button>  <button type="button" class="tabs-item" role="tab" id="tab-members" aria-selected="false" aria-controls="panel-members" tabindex="-1">    Members  </button></div><div role="tabpanel" tabindex="0" id="panel-profile" aria-labelledby="tab-profile" class="pt-md text-sm fg-text-body">  Profile settings</div><div role="tabpanel" tabindex="0" id="panel-billing" aria-labelledby="tab-billing" class="pt-md text-sm fg-text-body" hidden>  Billing settings</div><div role="tabpanel" tabindex="0" id="panel-members" aria-labelledby="tab-members" class="pt-md text-sm fg-text-body" hidden>  Members of the workspace</div><script type="module">  import { attach } from '@master/ui/behaviors'  attach()</script>
import { useEffect, useRef } from 'react'import { attach } from '@master/ui/behaviors'export function Example() {  const root = useRef<HTMLDivElement>(null)  useEffect(() => attach(root.current!), [])  return (    <div ref={root}>      <div className="tabs" role="tablist" aria-label="Account">        <button type="button" className="tabs-item" role="tab" id="tab-profile" aria-selected="true" aria-controls="panel-profile">          Profile        </button>        <button type="button" className="tabs-item" role="tab" id="tab-billing" aria-selected="false" aria-controls="panel-billing" tabIndex={-1}>          Billing        </button>        <button type="button" className="tabs-item" role="tab" id="tab-members" aria-selected="false" aria-controls="panel-members" tabIndex={-1}>          Members        </button>      </div>      <div role="tabpanel" tabIndex={0} id="panel-profile" aria-labelledby="tab-profile" className="pt-md text-sm fg-text-body">        Profile settings      </div>      <div role="tabpanel" tabIndex={0} id="panel-billing" aria-labelledby="tab-billing" className="pt-md text-sm fg-text-body" hidden>        Billing settings      </div>      <div role="tabpanel" tabIndex={0} id="panel-members" aria-labelledby="tab-members" className="pt-md text-sm fg-text-body" hidden>        Members of the workspace      </div>    </div>  )}
<script>  import { attach } from '@master/ui/behaviors'</script><div {@attach attach}>  <div class="tabs" role="tablist" aria-label="Account">    <button type="button" class="tabs-item" role="tab" id="tab-profile" aria-selected="true" aria-controls="panel-profile">      Profile    </button>    <button type="button" class="tabs-item" role="tab" id="tab-billing" aria-selected="false" aria-controls="panel-billing" tabindex="-1">      Billing    </button>    <button type="button" class="tabs-item" role="tab" id="tab-members" aria-selected="false" aria-controls="panel-members" tabindex="-1">      Members    </button>  </div>  <div role="tabpanel" tabindex="0" id="panel-profile" aria-labelledby="tab-profile" class="pt-md text-sm fg-text-body">    Profile settings  </div>  <div role="tabpanel" tabindex="0" id="panel-billing" aria-labelledby="tab-billing" class="pt-md text-sm fg-text-body" hidden>    Billing settings  </div>  <div role="tabpanel" tabindex="0" id="panel-members" aria-labelledby="tab-members" class="pt-md text-sm fg-text-body" hidden>    Members of the workspace  </div></div>
<script setup>import { onMounted, onUnmounted, ref } from 'vue'import { attach } from '@master/ui/behaviors'const root = ref(null)let detachonMounted(() => { detach = attach(root.value) })onUnmounted(() => detach?.())</script><template>  <div ref="root">    <div class="tabs" role="tablist" aria-label="Account">      <button type="button" class="tabs-item" role="tab" id="tab-profile" aria-selected="true" aria-controls="panel-profile">        Profile      </button>      <button type="button" class="tabs-item" role="tab" id="tab-billing" aria-selected="false" aria-controls="panel-billing" tabindex="-1">        Billing      </button>      <button type="button" class="tabs-item" role="tab" id="tab-members" aria-selected="false" aria-controls="panel-members" tabindex="-1">        Members      </button>    </div>    <div role="tabpanel" tabindex="0" id="panel-profile" aria-labelledby="tab-profile" class="pt-md text-sm fg-text-body">      Profile settings    </div>    <div role="tabpanel" tabindex="0" id="panel-billing" aria-labelledby="tab-billing" class="pt-md text-sm fg-text-body" hidden>      Billing settings    </div>    <div role="tabpanel" tabindex="0" id="panel-members" aria-labelledby="tab-members" class="pt-md text-sm fg-text-body" hidden>      Members of the workspace    </div>  </div></template>
탭에 포커스를 두고 방향키, Home 또는 End를 누르세요. 클릭으로도 선택할 수 있습니다.

tabs는 탭 목록을 받고 동작을 해제하는 함수를 반환합니다.

app.js
import { tabs } from '@master/ui/behaviors/tabs.js'const detach = tabs(document.querySelector('.tabs[role="tablist"]'))
  • 탭 키 포커스. 선택된 탭만 탭 키 탐색 순서에 포함됩니다. 방향키를 누르면 비활성화된 탭을 건너뛰어 앞이나 뒤의 탭으로 포커스를 옮기고 해당 탭을 선택합니다. 목록의 양 끝에서는 반대쪽 끝으로 이동합니다. Home과 End는 각각 첫 번째와 마지막 탭으로 이동합니다. aria-orientation="vertical"이 지정된 탭 목록에서는 위쪽과 아래쪽 방향키를 사용합니다.
  • 패널. 각 탭은 aria-controls로 자신이 제어하는 패널을 지정합니다. 선택된 탭의 패널을 표시하고 나머지 패널에는 hidden을 적용합니다.
  • 값. 다른 탭을 선택하면 탭 목록에서 input 이벤트와 change 이벤트가 차례로 발생하며, 두 이벤트 모두 버블링합니다. 두 이벤트의 detail.value에는 탭의 data-value 값이 들어가며, 해당 값이 없으면 탭의 텍스트가 들어갑니다. 동작이 반환하는 함수에도 같은 value가 있습니다. 이 값을 설정하면 외부에서 탭을 선택할 수 있으며, 이때는 이벤트가 발생하지 않습니다.
  • 스크립트가 없으면 선택된 탭의 패널만 hidden 속성 없이 표시되며, 패널 전환은 일어나지 않습니다. 각 탭을 별도 페이지로 구성할 수 있다면 nav 안에 링크를 사용합니다.

#검색할 수 있는 패널

tabs()의 두 번째 인수로 { searchable: true }를 전달하거나 프레임워크 컴포넌트의 searchable 속성을 설정하면, 텍스트가 많은 비활성 패널도 페이지 내 검색과 프래그먼트 탐색으로 열 수 있습니다. 네이티브 beforematch가 열린 패널의 탭을 선택하고 클릭과 같은 이벤트를 발생시킵니다. 숨겨진 패널이 공간을 차지하지 않도록 장식과 여백은 내부 요소에 지정합니다. beforematch를 지원하지 않는 브라우저에서는 일반적인 숨김 동작을 유지합니다.

#React, Svelte 및 Vue

tabs 컴포넌트는 데이터에서 탭 목록과 패널을 렌더링하고, 각 탭을 id로 해당 패널에 연결하며, 동작을 연결합니다. 선택된 탭 값을 입력으로 받고 외부로 전달합니다. nav 안에서 링크로 구성한 탭은 마크업으로 유지됩니다. npx master-ui add tabs로 컴포넌트를 프로젝트에 복사합니다. React, Svelte 및 Vue에서 컴포넌트의 구성과 사용법을 설명합니다.

ui/tabs.tsx
'use client'import { useId, useState, type ComponentProps, type ReactNode } from 'react'import { tabs } from '@master/ui/behaviors/tabs.js'import { useBehavior } from './use-behavior'export interface Tab {  /** What selecting the tab gives `onValueChange`. */  value: string  label: ReactNode  /** The panel the tab shows. */  content: ReactNode  disabled?: boolean}export interface TabsProps extends Omit<ComponentProps<'div'>, 'defaultValue' | 'children' | 'role' | 'ref'> {  tabs: Tab[]  /** The value of the selected tab. The first tab by default. */  value?: string  defaultValue?: string  onValueChange?: (value: string) => void  /** Let Find in Page and fragment links reveal inactive panels where supported. */  searchable?: boolean  /** Classes for each panel, such as its padding. */  panelClassName?: string}/** Tabs that switch panels in place. Name the tablist with `aria-label` or `aria-labelledby`. */export function Tabs({ tabs: list, value, defaultValue, onValueChange, searchable, panelClassName, className, ...root }: TabsProps) {  const id = useId()  const ref = useBehavior(tabs, { searchable }, { value, defaultValue, onValueChange: onValueChange as ((value: string | null) => void) | undefined })  const [first] = useState(value ?? defaultValue ?? list.find(tab => !tab.disabled)?.value)  return (    <>      <div className={className ? `tabs ${className}` : 'tabs'} role="tablist" ref={ref} {...root}>        {list.map((tab, index) => (          <button type="button" className="tabs-item" role="tab" key={tab.value} id={`${id}tab${index}`} data-value={tab.value} aria-selected={tab.value === first} aria-controls={`${id}panel${index}`} tabIndex={tab.value === first ? 0 : -1} disabled={tab.disabled}>{tab.label}</button>        ))}      </div>      {list.map((tab, index) => (        <div className={panelClassName} role="tabpanel" key={tab.value} id={`${id}panel${index}`} aria-labelledby={`${id}tab${index}`} hidden={tab.value !== first}>{tab.content}</div>      ))}    </>  )}
ui/Tabs.svelte
<script lang="ts" module>  import type { Snippet } from 'svelte'  import type { HTMLAttributes } from 'svelte/elements'  export interface Tab {    /** What selecting the tab gives `onValueChange`. */    value: string    label: string    /** The panel the tab shows, as text. Leave it out when `panel` writes it. */    content?: string    disabled?: boolean  }  export interface TabsProps extends Omit<HTMLAttributes<HTMLDivElement>, 'role' | 'children'> {    tabs: Tab[]    /** The value of the selected tab. Bind it, or leave it out: the first tab is selected. */    value?: string    onValueChange?: (value: string) => void    /** Let Find in Page and fragment links reveal inactive panels where supported. */    searchable?: boolean    /** Writes the panel of a tab, when it is more than text. */    panel?: Snippet<[Tab]>    /** Classes for each panel, such as its padding. */    panelClass?: string  }</script><script lang="ts">  import { untrack } from 'svelte'  import { tabs } from '@master/ui/behaviors/tabs.js'  import { behavior } from './behavior.svelte.js'  let { tabs: list, value = $bindable(), onValueChange, searchable, panel, panelClass, class: className, ...root }: TabsProps = $props()  const id = $props.id()  // The first value is drawn into the first render; after that the behavior marks the selected tab. A tab  // written later, from new tabs, is drawn with the value as it is then, which is not read as state.  const selected = { value: untrack(() => value ?? list.find(tab => !tab.disabled)?.value) }  const attach = behavior(tabs, () => ({ searchable }), {    value: () => value,    change: (next) => {      if (next === null) return      selected.value = next      value = next      onValueChange?.(next)    },    settled: (held) => { if (held !== null) selected.value = held },  })</script><!--  @component  Tabs that switch panels in place. Name the tablist with `aria-label` or `aria-labelledby`.--><div class={['tabs', className]} role="tablist" {@attach attach} {...root}>  {#each list as tab, index (tab.value)}    <button type="button" class="tabs-item" role="tab" id="{id}tab{index}" data-value={tab.value} aria-selected={tab.value === selected.value} aria-controls="{id}panel{index}" tabindex={tab.value === selected.value ? 0 : -1} disabled={tab.disabled}>{tab.label}</button>  {/each}</div>{#each list as tab, index (tab.value)}  <div class={panelClass} role="tabpanel" id="{id}panel{index}" aria-labelledby="{id}tab{index}" hidden={tab.value !== selected.value}>    {#if panel}{@render panel(tab)}{:else}{tab.content}{/if}  </div>{/each}
ui/Tabs.vue
<script lang="ts">export interface Tab {  /** What selecting the tab gives the model. */  value: string  label: string  /** The panel the tab shows, as text. The `panel` slot writes richer panels. */  content?: string  disabled?: boolean}</script><script setup lang="ts">import { useId, useTemplateRef } from 'vue'import { tabs as tablist } from '@master/ui/behaviors/tabs.js'import { useBehavior } from './use-behavior'defineOptions({ inheritAttrs: false })const props = defineProps<{  tabs: Tab[]  /** Let Find in Page and fragment links reveal inactive panels where supported. */  searchable?: boolean  /** Classes for each panel, such as its padding. */  panelClass?: string}>()/** The value of the selected tab: `v-model`. The first tab by default. */const model = defineModel<string>()defineSlots<{  /** What a tab's panel holds, in place of its `content`. */  panel?: (scope: { tab: Tab }) => unknown}>()/* Tabs that switch panels in place. Name the tablist with `aria-label` or `aria-labelledby`. */const id = useId()const first = model.value ?? props.tabs.find(tab => !tab.disabled)?.valueconst root = useTemplateRef<HTMLDivElement>('root')useBehavior(root, tablist, () => ({ searchable: props.searchable }), model)</script><template>  <div class="tabs" role="tablist" ref="root" v-bind="$attrs">    <button v-for="(tab, index) in tabs" :key="tab.value" type="button" class="tabs-item" role="tab" :id="`${id}-tab-${index}`" :data-value="tab.value" :aria-selected="tab.value === first" :aria-controls="`${id}-panel-${index}`" :tabindex="tab.value === first ? 0 : -1" :disabled="tab.disabled">{{ tab.label }}</button>  </div>  <div v-for="(tab, index) in tabs" :key="tab.value" v-bind="panelClass ? { class: panelClass } : {}" role="tabpanel" :id="`${id}-panel-${index}`" :aria-labelledby="`${id}-tab-${index}`" :hidden="tab.value !== first"><slot name="panel" :tab="tab">{{ tab.content }}</slot></div></template>

#클래스

클래스설명
tabs가는 선이 있는 탭 행입니다. 레이블이 있는 nav 또는 role="tablist"가 지정된 요소에 적용합니다. 탭이 한 줄에 다 들어가지 않으면 가로로 스크롤됩니다.
tabs-item탭에는 aria-current="page"가 지정된 링크나 role="tab"과 aria-selected가 지정된 버튼을 사용합니다
tabs-sm압축형 탭의 높이는 36px이고 레이블 글자 크기는 13px입니다. 기본값은 높이 44px, 레이블 글자 크기 14px입니다.적용할 클래스는 tabs입니다

#소스

@master/ui/components/tabs.css
/* * Tabs: words on one hairline; the current one is underlined in ink. * The current tab keeps its weight so the row never shifts between states. * With anchor positioning the underline is one mark that glides to the current tab. */@layer components.ui {  .tabs {    --tabs-item-height: 2.75rem;    --tabs-gap: 1.5rem;    --tabs-font-size: .875rem;    --icon-size: 1rem;    display: flex;    gap: 0 var(--tabs-gap);    overflow-x: auto;    overscroll-behavior-x: contain;    box-shadow: inset 0 -1px 0 var(--color-line-divider);    scrollbar-width: none;    /* The script listens on the whole row: a tap in the space between tabs must not flash it grey on iOS. */    -webkit-tap-highlight-color: transparent;    &.tabs-sm {      --tabs-item-height: 2.25rem;      --tabs-gap: 1rem;      --tabs-font-size: .8125rem;      --icon-size: .875rem;    }    @media (forced-colors: active) {      border-bottom: 1px solid CanvasText;    }  }  /* A tab: a link with aria-current="page", or a role="tab" button with aria-selected="true". */  .tabs-item {    display: inline-flex;    flex: none;    align-items: center;    gap: .375rem;    min-height: var(--tabs-item-height);    margin: 0;    padding: 0;    border: 0;    border-radius: 0;    background: none;    color: var(--color-text-muted);    font: 400 var(--tabs-font-size)/1.4 var(--font-family-sans);    font-feature-settings: inherit;    text-decoration: none;    white-space: nowrap;    appearance: none;    -webkit-tap-highlight-color: transparent;    cursor: pointer;    touch-action: manipulation;    transition-property: color, box-shadow;    transition-duration: var(--duration-quick);    transition-timing-function: var(--easing-glide);    user-select: none;    -webkit-user-select: none;    @media (hover: hover) {      &:hover:not(:disabled, [aria-disabled="true"]) {        color: var(--color-text-strong);      }    }    /* Pressed: the strong ink, as under the pointer, so a tap is answered too. */    &:active:not(:disabled, [aria-disabled="true"]) {      color: var(--color-text-strong);    }    &:is([aria-current="page"], [aria-selected="true"]) {      color: var(--color-text-strong);      box-shadow: inset 0 -2px 0 var(--color-text-strong);    }    &:focus-visible {      @apply --focus-ring;      outline-offset: -2px;      border-radius: calc((var(--radius-chip) - 2px) * var(--corner-scale));      corner-shape: var(--corner-shape);    }    /*     * Disabled: the disabled ink and no answer to the pointer. It still takes the pointer, so a tooltip that says     * why it is unavailable can be reached on it.     */    &:is(:disabled, [aria-disabled="true"]) {      color: var(--color-text-disabled);      cursor: not-allowed;    }    @media (forced-colors: active) {      &:is([aria-current="page"], [aria-selected="true"]) {        border-bottom: 2px solid Highlight;      }    }  }  /*   * The gliding underline. The current tab names itself as an anchor; the row scopes that name and draws one   * mark between the anchor's edges, with a softened top so the ink does not end in a hard corner.   */  @supports (anchor-scope: --tabs-mark) {    .tabs {      position: relative;      anchor-scope: --tabs-mark;      &:has(.tabs-item:is([aria-current="page"], [aria-selected="true"]))::after {        content: '';        position: absolute;        position-anchor: --tabs-mark;        right: anchor(right);        bottom: 0;        left: anchor(left);        height: 2px;        border-radius: 2px 2px 0 0;        background: var(--color-text-strong);        pointer-events: none;        transition-property: right, left;        transition-duration: var(--duration-base);        transition-timing-function: var(--easing-glide);      }      /* As heavy as the rule that glides, or the glide outweighs it. */      @media (prefers-reduced-motion: reduce) {        &:has(.tabs-item:is([aria-current="page"], [aria-selected="true"]))::after {          transition: none;        }      }      @media (forced-colors: active) {        &::after {          display: none;        }      }    }    .tabs-item:is([aria-current="page"], [aria-selected="true"]) {      anchor-name: --tabs-mark;      box-shadow: none;    }  }}