Class Names
The Class Names plugin adds a layer of automation for managing CSS classes on your carousel elements. It allows you to easily style slides and the container based on their state, such as when a slide is selected, visible, or when the carousel is being dragged.
Installation
To use class names automation, you need to install the embla-carousel-class-names package:
npm install embla-carousel-class-names
Usage
Pass the ClassNames() plugin to the Embla Carousel constructor. By default, it will toggle classes like is-selected and is-draggable.
Vanilla JavaScript
import EmblaCarousel from 'embla-carousel'
import ClassNames from 'embla-carousel-class-names'
const emblaApi = EmblaCarousel(viewportNode, { loop: true }, [ClassNames()])
React
import useEmblaCarousel from 'embla-carousel-react'
import ClassNames from 'embla-carousel-class-names'
export function EmblaCarousel() {
const [emblaRef] = useEmblaCarousel({ loop: true }, [ClassNames()])
return (
<div className="embla" ref={emblaRef}>
<div className="embla__container">
<div className="embla__slide">Slide 1</div>
<div className="embla__slide">Slide 2</div>
</div>
</div>
)
}
Options
The plugin accepts an options object to customize the class names and behavior.
| Option | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| selected | string | 'is-selected' | Class added to the selected slide(s). |
| inView | string | 'is-in-view' | Class added to slides currently in the viewport. |
| draggable | string | 'is-draggable' | Class added to the container when it is draggable. |
| dragging | string | 'is-dragging' | Class added to the container while actively dragging. |
Example Configuration
const options = {
selected: 'my-custom-selected-class',
inView: 'my-custom-in-view-class',
}
const emblaApi = EmblaCarousel(viewportNode, {}, [ClassNames(options)])
Technical Details
In-View Threshold
The inView class relies on the inViewThreshold and inViewMargin options from the Embla Carousel core. If a slide meets the intersection criteria defined in the core options, the plugin will apply the inView class.
Snapping and Selection
The selected class is applied to the slide(s) that match the current snap point. In a carousel with slidesToScroll: 1, this is typically a single slide. If slidesToScroll is higher, multiple slides may receive the class simultaneously.
Types
export type ClassNamesOptionsType = {
selected?: string
draggable?: string
dragging?: string
inView?: string
}
Manual Implementation
If you prefer not to use a plugin, you can achieve similar results using the Embla API events select, slidesInView, and pointerDown/pointerUp:
emblaApi.on('select', (api) => {
const selectedIndex = api.selectedSnap()
// Manually toggle classes on api.slideNodes()
})