Skip to content
WebJs
Menu

A carousel with motion and swipe built on CSS scroll snap.

1
2
3
4
5
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { cardClass, cardContentClass } from '#components/ui/card.ts';

export default function CarouselDemo() {
  return html`
    <ui-carousel class="w-full max-w-[12rem] sm:max-w-xs">
      <ui-carousel-content>
        ${Array.from({ length: 5 }).map((_, index) => html`
          <ui-carousel-item>
            <div class="p-1">
              <div data-slot="card" data-size="default" class=${cardClass()}>
                <div data-slot="card-content" class=${cn(cardContentClass(), 'flex aspect-square items-center justify-center p-6')}>
                  <span class="text-4xl font-semibold">${index + 1}</span>
                </div>
              </div>
            </div>
          </ui-carousel-item>
        `)}
      </ui-carousel-content>
      <ui-carousel-previous></ui-carousel-previous>
      <ui-carousel-next></ui-carousel-next>
    </ui-carousel>
  `;
}
View Code

About

The carousel component is built on CSS scroll snap, so the slides scroll and snap natively by touch, trackpad and wheel with no JavaScript. The <ui-carousel> element adds the previous and next buttons, the arrow keys, and methods for stepping through the slides.

Installation

pnpm dlx @webjsdev/ui add carousel

Usage

import '#components/ui/carousel.ts';
<ui-carousel>
  <ui-carousel-content>
    <ui-carousel-item>...</ui-carousel-item>
    <ui-carousel-item>...</ui-carousel-item>
    <ui-carousel-item>...</ui-carousel-item>
  </ui-carousel-content>
  <ui-carousel-previous></ui-carousel-previous>
  <ui-carousel-next></ui-carousel-next>
</ui-carousel>

Composition

Use the following composition to build a carousel:

ui-carousel
├── ui-carousel-content
│   ├── ui-carousel-item
│   └── ui-carousel-item
├── ui-carousel-previous
└── ui-carousel-next

Sizes

To set the size of the items, you can use the basis utility class on the <ui-carousel-item>.

1
2
3
4
5
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { cardClass, cardContentClass } from '#components/ui/card.ts';

export default function CarouselSize() {
  return html`
    <ui-carousel class="w-full max-w-[12rem] sm:max-w-xs md:max-w-sm">
      <ui-carousel-content>
        ${Array.from({ length: 5 }).map((_, index) => html`
          <ui-carousel-item class="basis-1/2 lg:basis-1/3">
            <div class="p-1">
              <div data-slot="card" data-size="default" class=${cardClass()}>
                <div data-slot="card-content" class=${cn(cardContentClass(), 'flex aspect-square items-center justify-center p-6')}>
                  <span class="text-3xl font-semibold">${index + 1}</span>
                </div>
              </div>
            </div>
          </ui-carousel-item>
        `)}
      </ui-carousel-content>
      <ui-carousel-previous></ui-carousel-previous>
      <ui-carousel-next></ui-carousel-next>
    </ui-carousel>
  `;
}
View Code
<!-- 33% of the carousel width. -->
<ui-carousel>
  <ui-carousel-content>
    <ui-carousel-item class="basis-1/3">...</ui-carousel-item>
    <ui-carousel-item class="basis-1/3">...</ui-carousel-item>
    <ui-carousel-item class="basis-1/3">...</ui-carousel-item>
  </ui-carousel-content>
</ui-carousel>
<!-- 50% on small screens and 33% on larger screens. -->
<ui-carousel>
  <ui-carousel-content>
    <ui-carousel-item class="md:basis-1/2 lg:basis-1/3">...</ui-carousel-item>
    <ui-carousel-item class="md:basis-1/2 lg:basis-1/3">...</ui-carousel-item>
    <ui-carousel-item class="md:basis-1/2 lg:basis-1/3">...</ui-carousel-item>
  </ui-carousel-content>
</ui-carousel>

Spacing

Each item carries a start padding and the track inside <ui-carousel-content> a matching negative start margin, ps-4 and -ms-4 by default. To change the spacing, set a ps-[VALUE] utility on the <ui-carousel-item> and the negative margin on the track from <ui-carousel-content>.

1
2
3
4
5
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { cardClass, cardContentClass } from '#components/ui/card.ts';

export default function CarouselSpacing() {
  return html`
    <ui-carousel class="w-full max-w-[12rem] sm:max-w-xs md:max-w-sm">
      <ui-carousel-content class="[&_[data-slot=carousel-content]>div]:-ms-1">
        ${Array.from({ length: 5 }).map((_, index) => html`
          <ui-carousel-item class="basis-1/2 ps-1 lg:basis-1/3">
            <div class="p-1">
              <div data-slot="card" data-size="default" class=${cardClass()}>
                <div data-slot="card-content" class=${cn(cardContentClass(), 'flex aspect-square items-center justify-center p-6')}>
                  <span class="text-2xl font-semibold">${index + 1}</span>
                </div>
              </div>
            </div>
          </ui-carousel-item>
        `)}
      </ui-carousel-content>
      <ui-carousel-previous></ui-carousel-previous>
      <ui-carousel-next></ui-carousel-next>
    </ui-carousel>
  `;
}
View Code
<ui-carousel>
  <ui-carousel-content class="[&_[data-slot=carousel-content]>div]:-ms-4">
    <ui-carousel-item class="ps-4">...</ui-carousel-item>
    <ui-carousel-item class="ps-4">...</ui-carousel-item>
    <ui-carousel-item class="ps-4">...</ui-carousel-item>
  </ui-carousel-content>
</ui-carousel>
<ui-carousel>
  <ui-carousel-content class="[&_[data-slot=carousel-content]>div]:-ms-2 md:[&_[data-slot=carousel-content]>div]:-ms-4">
    <ui-carousel-item class="ps-2 md:ps-4">...</ui-carousel-item>
    <ui-carousel-item class="ps-2 md:ps-4">...</ui-carousel-item>
    <ui-carousel-item class="ps-2 md:ps-4">...</ui-carousel-item>
  </ui-carousel-content>
</ui-carousel>

Orientation

Use the orientation attribute to set the orientation of the carousel. A vertical carousel needs a height on <ui-carousel-content>.

1
2
3
4
5
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { cardClass, cardContentClass } from '#components/ui/card.ts';

// A vertical carousel takes its height on <ui-carousel-content>. The track
// inside it carries the negative margin that pairs with each slide's padding.
export default function CarouselOrientation() {
  return html`
    <ui-carousel orientation="vertical" class="w-full max-w-xs">
      <ui-carousel-content class="h-[270px] [&_[data-slot=carousel-content]>div]:-mt-1">
        ${Array.from({ length: 5 }).map((_, index) => html`
          <ui-carousel-item class="basis-1/2 pt-1">
            <div class="p-1">
              <div data-slot="card" data-size="default" class=${cardClass()}>
                <div data-slot="card-content" class=${cn(cardContentClass(), 'flex items-center justify-center p-6')}>
                  <span class="text-3xl font-semibold">${index + 1}</span>
                </div>
              </div>
            </div>
          </ui-carousel-item>
        `)}
      </ui-carousel-content>
      <ui-carousel-previous></ui-carousel-previous>
      <ui-carousel-next></ui-carousel-next>
    </ui-carousel>
  `;
}
View Code
<ui-carousel orientation="vertical | horizontal">
  <ui-carousel-content>
    <ui-carousel-item>...</ui-carousel-item>
    <ui-carousel-item>...</ui-carousel-item>
    <ui-carousel-item>...</ui-carousel-item>
  </ui-carousel-content>
</ui-carousel>

Options

The carousel is native CSS scroll snap, and slides snap to their start. The one option is the loop attribute, which makes the previous and next buttons (and the arrow keys) wrap around at the ends.

<ui-carousel loop>
  <ui-carousel-content>
    <ui-carousel-item>...</ui-carousel-item>
    <ui-carousel-item>...</ui-carousel-item>
    <ui-carousel-item>...</ui-carousel-item>
  </ui-carousel-content>
</ui-carousel>

API

The <ui-carousel> element is the API: query it and call its methods, or read its state.

1
2
3
4
5
Slide 1 of 5
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { cardClass, cardContentClass } from '#components/ui/card.ts';

// The counter shows the first paint. In an app, a component listens for the
// carousel's ui-slide-change event and writes detail.index + 1 into it.
export default function CarouselApi() {
  const count = 5;
  const current = 1;

  return html`
    <div class="mx-auto max-w-[10rem] sm:max-w-xs">
      <ui-carousel class="w-full max-w-xs">
        <ui-carousel-content>
          ${Array.from({ length: count }).map((_, index) => html`
            <ui-carousel-item>
              <div data-slot="card" data-size="default" class=${cn(cardClass(), 'm-px')}>
                <div data-slot="card-content" class=${cn(cardContentClass(), 'flex aspect-square items-center justify-center p-6')}>
                  <span class="text-4xl font-semibold">${index + 1}</span>
                </div>
              </div>
            </ui-carousel-item>
          `)}
        </ui-carousel-content>
        <ui-carousel-previous></ui-carousel-previous>
        <ui-carousel-next></ui-carousel-next>
      </ui-carousel>
      <div class="py-2 text-center text-sm text-muted-foreground">
        Slide ${current} of ${count}
      </div>
    </div>
  `;
}
View Code
import { WebComponent, html, signal } from '@webjsdev/core';
import '#components/ui/carousel.ts';

class SlideCounter extends WebComponent {
  current = signal(1);
  count = signal(0);

  firstUpdated() {
    const carousel = this.querySelector('ui-carousel')!;
    this.count.set(carousel.querySelectorAll('ui-carousel-item').length);
    this.current.set(carousel.selectedIndex + 1);
  }

  render() {
    return html`
      <ui-carousel @ui-slide-change=${(e: CustomEvent<{ index: number }>) => this.current.set(e.detail.index + 1)}>
        <ui-carousel-content>
          <ui-carousel-item>...</ui-carousel-item>
          <ui-carousel-item>...</ui-carousel-item>
          <ui-carousel-item>...</ui-carousel-item>
        </ui-carousel-content>
      </ui-carousel>
      <div>Slide ${this.current.get()} of ${this.count.get()}</div>
    `;
  }
}
SlideCounter.register('slide-counter');

Events

The carousel dispatches a bubbling ui-slide-change event whenever the selected slide changes, with the new index in detail.index.

const carousel = document.querySelector('ui-carousel');

carousel.addEventListener('ui-slide-change', (e) => {
  // Do something on select.
  console.log(e.detail.index);
});

Plugins

Add behaviour such as autoplay with a few lines in a component of your own that steps the carousel with scrollNext(), here with loop so it wraps back to the first slide.

import { WebComponent, html } from '@webjsdev/core';
import '#components/ui/carousel.ts';

class AutoplayCarousel extends WebComponent {
  timer = 0;

  connectedCallback() {
    super.connectedCallback();
    const carousel = this.querySelector('ui-carousel')!;
    this.timer = window.setInterval(() => carousel.scrollNext(), 2000);
    // Stop on interaction.
    carousel.addEventListener('pointerdown', () => clearInterval(this.timer), { once: true });
  }

  disconnectedCallback() {
    clearInterval(this.timer);
    super.disconnectedCallback();
  }

  render() {
    return html`<ui-carousel loop>...</ui-carousel>`;
  }
}
AutoplayCarousel.register('autoplay-carousel');
1
2
3
4
5
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { cardClass, cardContentClass } from '#components/ui/card.ts';

// The kit has no plugin system. Autoplay is a few lines in a component of
// your own that calls the carousel's scrollNext() on a timer (see the docs).
export default function CarouselPlugin() {
  return html`
    <ui-carousel loop class="w-full max-w-[10rem] sm:max-w-xs">
      <ui-carousel-content>
        ${Array.from({ length: 5 }).map((_, index) => html`
          <ui-carousel-item>
            <div class="p-1">
              <div data-slot="card" data-size="default" class=${cardClass()}>
                <div data-slot="card-content" class=${cn(cardContentClass(), 'flex aspect-square items-center justify-center p-6')}>
                  <span class="text-4xl font-semibold">${index + 1}</span>
                </div>
              </div>
            </div>
          </ui-carousel-item>
        `)}
      </ui-carousel-content>
      <ui-carousel-previous></ui-carousel-previous>
      <ui-carousel-next></ui-carousel-next>
    </ui-carousel>
  `;
}
View Code

RTL

To enable RTL support, see the RTL configuration guide.

١
٢
٣
٤
٥
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { cardClass, cardContentClass } from '#components/ui/card.ts';

const translations = {
  en: { dir: 'ltr' },
  ar: { dir: 'rtl' },
  he: { dir: 'rtl' },
};

function toArabicNumerals(num: number): string {
  const arabicNumerals = ['٠', '١', '٢', '٣', '٤', '٥', '٦', '٧', '٨', '٩'];
  return num
    .toString()
    .split('')
    .map((digit) => arabicNumerals[parseInt(digit, 10)])
    .join('');
}

// dir="rtl" is the whole switch: the carousel reads its direction from the
// page, so it scrolls, steps and flips its arrows to match.
export default function CarouselRtl() {
  const language = 'ar';
  const { dir } = translations[language];
  const formatNumber = (num: number): string => (language === 'ar' ? toArabicNumerals(num) : num.toString());

  return html`
    <ui-carousel dir=${dir} class="w-full max-w-[12rem] sm:max-w-xs">
      <ui-carousel-content>
        ${Array.from({ length: 5 }).map((_, index) => html`
          <ui-carousel-item>
            <div class="p-1">
              <div data-slot="card" data-size="default" dir=${dir} class=${cardClass()}>
                <div data-slot="card-content" class=${cn(cardContentClass(), 'flex aspect-square items-center justify-center p-6')}>
                  <span class="text-4xl font-semibold">${formatNumber(index + 1)}</span>
                </div>
              </div>
            </div>
          </ui-carousel-item>
        `)}
      </ui-carousel-content>
      <ui-carousel-previous></ui-carousel-previous>
      <ui-carousel-next></ui-carousel-next>
    </ui-carousel>
  `;
}
View Code

When localizing the carousel for RTL languages, set dir on the carousel or any ancestor. The carousel reads its direction from the page, so it scrolls the right way, the arrow keys swap, and the navigation buttons flip their icons on their own.

<ui-carousel dir="rtl">
  <ui-carousel-content>
    <ui-carousel-item>...</ui-carousel-item>
    <ui-carousel-item>...</ui-carousel-item>
    <ui-carousel-item>...</ui-carousel-item>
  </ui-carousel-content>
  <ui-carousel-previous></ui-carousel-previous>
  <ui-carousel-next></ui-carousel-next>
</ui-carousel>

API Reference

The root. It renders a role="region" with aria-roledescription="carousel"; name it with aria-label.

AttributeTypeDefault
orientation"horizontal" | "vertical""horizontal"
loopbooleanfalse
aria-labelstring-
MemberTypeDescription
scrollPrev()() => voidStep back one slide (to the last with loop).
scrollNext()() => voidStep on one slide (to the first with loop).
scrollTo(index)(index: number) => voidScroll slide index to the start.
selectedIndexnumberThe slide nearest the start.
canScrollPrevbooleanWhether there is a slide before.
canScrollNextbooleanWhether there is a slide after.
EventDetailDescription
ui-slide-change{ index: number }The selected slide changed.

The scroller. It holds the slides and takes the height of a vertical carousel.

One slide, a role="group" with aria-roledescription="slide". Size it with a basis-* class.

The buttons, named "Previous slide" and "Next slide" and disabled at the ends. They sit outside the carousel's edges, so leave room beside it.

AttributeTypeDefault
variant"default" | "outline" | "ghost" | "destructive" | "secondary" | "link""outline"
size"default" | "xs" | "sm" | "lg" | "icon" | "icon-xs" | "icon-sm" | "icon-lg""icon-sm"