diff --git a/src/components/carousel/carousel.ts b/src/components/carousel/carousel.ts index 4ee58e04a..7ca326ba3 100644 --- a/src/components/carousel/carousel.ts +++ b/src/components/carousel/carousel.ts @@ -344,7 +344,7 @@ export default class SlCarousel extends ShoelaceElement { * @param behavior - The behavior used for scrolling. */ goToSlide(index: number, behavior: ScrollBehavior = 'smooth') { - const { slidesPerPage, loop } = this; + const { slidesPerPage, loop, scrollContainer } = this; const slides = this.getSlides(); const slidesWithClones = this.getSlides({ excludeClones: false }); @@ -358,9 +358,12 @@ export default class SlCarousel extends ShoelaceElement { const nextSlideIndex = clamp(index + (loop ? slidesPerPage : 0), 0, slidesWithClones.length - 1); const nextSlide = slidesWithClones[nextSlideIndex]; - this.scrollContainer.scrollTo({ - left: nextSlide.offsetLeft, - top: nextSlide.offsetTop, + const scrollContainerRect = scrollContainer.getBoundingClientRect(); + const nextSlideRect = nextSlide.getBoundingClientRect(); + + scrollContainer.scrollTo({ + left: nextSlideRect.left - scrollContainerRect.left + scrollContainer.scrollLeft, + top: nextSlideRect.top - scrollContainerRect.top + scrollContainer.scrollTop, behavior: prefersReducedMotion() ? 'auto' : behavior }); }