Virtual Slides in Swiper.js: Container Height Fails to Recalculate After Dynamic Content Change
0 reputation · 02 May 2020, 05:36 UTC
0 reputation · 02 May 2020, 05:36 UTC
When using Swiper.js with the Virtual Slides module in vertical mode, the container height does not adjust after the content of a slide changes post‑initialization.
The instance is configured with virtual: true, direction: 'vertical', and slidesPerView: 'auto'. The issue appears in Swiper 8.x and 9.x.
1. Does Swiper’s Virtual Slides module recalculate the container height automatically when the inner content of a rendered slide changes?
2. If not, is there a documented event or method that should be called to trigger a height update?
3. Does the problem persist when using slidesPerView: 1 instead of 'auto'?
29275 reputation · 02 May 2020, 16:54 UTC
Swiper's Virtual Slides module does not automatically recalculate container height when the content of an already-rendered slide changes after initialization. The height is measured during the initial render and only refreshed when you explicitly ask Swiper to update.
observer: true or observeParents: true, the MutationObserver only watches for structural changes (slides added or removed), not inner content or size changes within an existing slide.swiper.update() after the content change. For finer control, swiper.updateSize() followed by swiper.updateSlides() re-reads dimensions and resizes the wrapper. There is no dedicated event such as slideContentChange.slidesPerView: 1 fix it? It often masks the symptom, because Swiper re-fits the container to the active slide on each slideChangeTransitionEnd. But a mid-slide content growth still goes unnoticed until the next slide change or an explicit update().After any async injection, image load, or CSS-driven height change, call update() inside requestAnimationFrame to avoid layout thrashing:
// After mutating slide content
requestAnimationFrame(() => {
swiper.update();
});
// For images inside a slide
slideEl.querySelectorAll('img').forEach((img) => {
img.addEventListener('load', () => swiper.update(), { once: true });
});
height: auto. Fixed heights or overflow: hidden on the slide element prevent correct measurement, especially with slidesPerView: 'auto' in vertical mode.update() in a tight loop (e.g., an undebounced resize handler); debounce it.update() re-renders the visible slide range, so keep your renderSlide function idempotent and fast.Build a minimal vertical Swiper with virtual: true and slidesPerView: 'auto', then grow a slide via setTimeout(() => slideEl.style.height = '200px', 1000). The wrapper height should stay unchanged until swiper.update() runs. Repeat with slidesPerView: 1: the wrapper resizes only on the next slide transition, confirming the behavior is consistent across Swiper 8.x and 9.x.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.