Data Table

6 people

Team members, sortable by column
Maya ChenDesignLisbonActive
Daniel OkaforEngineeringLagosActive
Ava MartinezProductMadridAway
Leo NovakEngineeringPragueOffline
Sara KimMarketingSeoulActive
Omar HaddadDesignAmmanAway
@use 'sprucecss/scss/spruce' as *;

.data-table {
  @include layout-stack('s');

  &__toolbar {
    align-items: center;
    display: flex;
    flex-wrap: wrap;
    gap: spacer('s');
    justify-content: space-between;
  }

  &__filter {
    max-inline-size: 20rem;
  }

  &__summary,
  &__empty {
    color: color('muted');
    font-size: config('font-size-sm', $typography);
  }

  &__summary {
    margin-block: 0;
  }

  &__empty {
    padding: spacer('m');
    text-align: center;
  }

  &__sort {
    @include clear-btn;
    align-items: center;
    display: inline-flex;
    font-weight: inherit;
    gap: spacer('xxs');
    white-space: nowrap;

    &:focus-visible {
      border-radius: radius('sm');
      outline: 2px solid color('focus-ring');
      outline-offset: 2px;
    }
  }

  &__sort-icon {
    block-size: 0.75em;
    inline-size: 0.5em;
    opacity: 0.35;
    position: relative;

    &::before,
    &::after {
      border-inline: 0.25em solid transparent;
      content: '';
      inset-inline-start: 0;
      position: absolute;
    }

    &::before {
      border-block-end: 0.3em solid currentcolor;
      inset-block-start: 0;
    }

    &::after {
      border-block-start: 0.3em solid currentcolor;
      inset-block-end: 0;
    }
  }

  th[aria-sort='ascending'] &__sort-icon,
  th[aria-sort='descending'] &__sort-icon {
    opacity: 1;
  }

  th[aria-sort='ascending'] &__sort-icon::after,
  th[aria-sort='descending'] &__sort-icon::before {
    opacity: 0;
  }

  &__status {
    --status-color: #{color('success', 'alert')};
    align-items: center;
    display: inline-flex;
    font-size: config('font-size-sm', $typography);
    gap: spacer('xxs');

    &::before {
      background-color: var(--status-color);
      block-size: 0.5rem;
      border-radius: 50%;
      content: '';
      inline-size: 0.5rem;
    }

    &--away {
      --status-color: #{color('warning', 'alert')};
    }

    &--offline {
      --status-color: #{color('border-strong')};
    }
  }
}
<div class="data-table" data-data-table>
    <div class="data-table__toolbar">
        <label class="sr-only" for="data-table-filter">Filter people</label>
        <input class="form-control form-control--sm data-table__filter" id="data-table-filter" type="search" placeholder="Filter by name, team or city…" data-table-filter>
        <p class="data-table__summary" aria-live="polite" data-table-summary>6 people</p>
    </div>
    <div class="table-responsive">
        <table class="table table--hover table--middle">
            <caption class="sr-only">Team members, sortable by column</caption>
            <thead>
                <tr>
                    <th scope="col" aria-sort="none"><button class="data-table__sort" type="button" data-sort="0" data-type="text">Name<span class="data-table__sort-icon" aria-hidden="true"></span></button></th>
                    <th scope="col" aria-sort="none"><button class="data-table__sort" type="button" data-sort="1" data-type="text">Team<span class="data-table__sort-icon" aria-hidden="true"></span></button></th>
                    <th scope="col" aria-sort="none"><button class="data-table__sort" type="button" data-sort="2" data-type="text">City<span class="data-table__sort-icon" aria-hidden="true"></span></button></th>
                    <th scope="col" aria-sort="none"><button class="data-table__sort" type="button" data-sort="3" data-type="date">Joined<span class="data-table__sort-icon" aria-hidden="true"></span></button></th>
                    <th scope="col" aria-sort="none"><button class="data-table__sort" type="button" data-sort="4" data-type="text">Status<span class="data-table__sort-icon" aria-hidden="true"></span></button></th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>Maya Chen</td>
                    <td>Design</td>
                    <td>Lisbon</td>
                    <td><time datetime="2021-03-14">2021-03-14</time></td>
                    <td><span class="data-table__status data-table__status--active">Active</span></td>
                </tr>
                <tr>
                    <td>Daniel Okafor</td>
                    <td>Engineering</td>
                    <td>Lagos</td>
                    <td><time datetime="2019-11-02">2019-11-02</time></td>
                    <td><span class="data-table__status data-table__status--active">Active</span></td>
                </tr>
                <tr>
                    <td>Ava Martinez</td>
                    <td>Product</td>
                    <td>Madrid</td>
                    <td><time datetime="2023-06-21">2023-06-21</time></td>
                    <td><span class="data-table__status data-table__status--away">Away</span></td>
                </tr>
                <tr>
                    <td>Leo Novak</td>
                    <td>Engineering</td>
                    <td>Prague</td>
                    <td><time datetime="2020-01-09">2020-01-09</time></td>
                    <td><span class="data-table__status data-table__status--offline">Offline</span></td>
                </tr>
                <tr>
                    <td>Sara Kim</td>
                    <td>Marketing</td>
                    <td>Seoul</td>
                    <td><time datetime="2022-08-30">2022-08-30</time></td>
                    <td><span class="data-table__status data-table__status--active">Active</span></td>
                </tr>
                <tr>
                    <td>Omar Haddad</td>
                    <td>Design</td>
                    <td>Amman</td>
                    <td><time datetime="2024-02-12">2024-02-12</time></td>
                    <td><span class="data-table__status data-table__status--away">Away</span></td>
                </tr>
            </tbody>
        </table>
    </div>
    <p class="data-table__empty" hidden data-table-empty>No people match your filter.</p>
</div>
(() => {
  const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' });

  document.querySelectorAll('[data-data-table]').forEach((component) => {
    const tbody = component.querySelector('tbody');
    const rows = [...tbody.rows];
    const filter = component.querySelector('[data-table-filter]');
    const summary = component.querySelector('[data-table-summary]');
    const empty = component.querySelector('[data-table-empty]');

    component.querySelectorAll('[data-sort]').forEach((button) => {
      button.addEventListener('click', () => {
        const header = button.closest('th');
        const column = Number(button.dataset.sort);
        const isDate = button.dataset.type === 'date';
        const direction = header.getAttribute('aria-sort') === 'ascending' ? 'descending' : 'ascending';
        const modifier = direction === 'ascending' ? 1 : -1;

        component.querySelectorAll('th[aria-sort]').forEach((th) => th.setAttribute('aria-sort', 'none'));
        header.setAttribute('aria-sort', direction);

        rows
          .sort((a, b) => {
            const first = a.cells[column].textContent.trim();
            const second = b.cells[column].textContent.trim();

            return (isDate ? new Date(first) - new Date(second) : collator.compare(first, second)) * modifier;
          })
          .forEach((row) => tbody.append(row));
      });
    });

    filter?.addEventListener('input', () => {
      const query = filter.value.trim().toLowerCase();
      let visible = 0;

      rows.forEach((row) => {
        const isMatch = row.textContent.toLowerCase().includes(query);

        row.hidden = !isMatch;
        visible += isMatch ? 1 : 0;
      });

      summary.textContent = `${visible} ${visible === 1 ? 'person' : 'people'}`;
      empty.hidden = visible > 0;
    });
  });
})();

Data Table

On this page

A sortable, filterable data table built on Spruce's `.table` styles and a few lines of vanilla JavaScript.

Technical Details

  • The sort controls are real buttons inside the column headers; the header's aria-sort attribute reflects the state (ascending, descending, none), which screen readers announce.
  • Text columns sort with Intl.Collator (locale and number aware); data-type="date" columns sort chronologically.
  • The filter input updates a polite live region with the number of matching rows and shows an empty-state message when nothing matches.
  • The table is wrapped in .table-responsive, so it scrolls horizontally on small screens. Without JavaScript, it is a regular readable table.

Documentation

Learn about Spruce CSS through our extensive documentation.

Components

Explore our UI library of accessible components built with Spruce CSS.

Blocks and Pages

Full-width page blocks and complete page templates, ready to copy.

Find us on GitHub

Did you find a bug? Have an idea or a question? Please open an issue to help us develop the project.