Auto Height
The Auto Height plugin allows Embla Carousel to dynamically adjust the height of the viewport to match the height of the currently selected slide. This is particularly useful for carousels where slides contain varying amounts of content.
Installation
First, install the embla-carousel-auto-height package via your preferred package manager:
npm install embla-carousel-auto-height --save
Usage
The plugin is initialized by passing it to the third argument of the Embla constructor (for Vanilla JS) or the second argument of framework hooks.
Vanilla JS
import EmblaCarousel from 'embla-carousel'
import AutoHeight from 'embla-carousel-auto-height'
const viewportNode = document.querySelector('.embla__viewport')
const emblaApi = EmblaCarousel(viewportNode, { loop: true }, [AutoHeight()])
React
import useEmblaCarousel from 'embla-carousel-react'
import AutoHeight from 'embla-carousel-auto-height'
export function EmblaCarousel() {
const [emblaRef] = useEmblaCarousel({ loop: true }, [AutoHeight()])
return (
<div className="embla" ref={emblaRef}>
<div className="embla__container">
<div className="embla__slide">Slide 1</div>
<div className="embla__slide">Slide 2 (taller content)</div>
</div>
</div>
)
}
Options
The AutoHeight plugin accepts an optional configuration object:
| Option | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| destroyHeight | string | 'auto' | The height value applied to the viewport when the plugin is destroyed or becomes inactive. |
AutoHeight({
destroyHeight: 'auto'
})
CSS Requirements
For the height transition to appear smooth, you should add a transition property to the viewport element in your CSS. Without this, the height will jump instantly to the new value.
.embla__viewport {
overflow: hidden;
width: 100%;
transition: height 0.2s; /* Adjust duration and easing as needed */
}
API
The Auto Height plugin exposes its own API to interact with its state. You can access it via the plugins() method on the main Embla API:
const autoHeightApi = emblaApi.plugins().autoHeight
// Force the plugin to re-calculate the height
autoHeightApi.reInit()
Methods
reInit()
Triggers a manual recalculation of the viewport height based on the current slide. This is useful if the content within the active slide changes dynamically (e.g., loading an image or expanding an accordion).
destroy()
Removes all event listeners and resets the viewport height to the destroyHeight value.