RTL carousels: direction, swipe and arrows
Build RTL carousels with matching slide order, swipe gestures, arrow buttons and progress dots, and test focus and autoplay behavior.
By Omran Khleifat, Founder of Ritla
Guide13 min read
An Arabic carousel can show its first card on the right and still send the next card out of view. The layout has followed dir="rtl"; the animation is still subtracting an English horizontal offset. Reversing the arrows makes the controls look different without repairing that movement.
For a horizontal carousel that follows Arabic reading order, keep the content sequence intact, place later slides to the left, and make every navigation method advance through that same sequence. A geological trail guide, for example, should present its introduction, rock formations and viewpoint in that order in both languages.
The distinction that prevents several bugs is this: the next slide lies to the left in RTL, but the track moves right to bring it into view. With direct dragging, the finger also moves right. “Next,” the direction of travel through the content, and the physical movement of the track are separate concepts.
Define next before changing the animation#
Use a logical index: the introduction is index zero, formations follow it, and the viewpoint comes last. Next increases that index regardless of language. Previous decreases it. Direction determines where those slides sit and how the viewport reaches them.
For a conventional horizontal sequence with direct manipulation, the expected relationships are:
| Behavior | LTR interface | RTL interface |
|---|---|---|
| First slide begins at | Left/start edge | Right/start edge |
| Later slide is positioned toward | Left-to-right progression | Right-to-left progression |
| Next arrow points toward | Right | Left |
| Track moves to reveal next | Left | Right |
| Finger drags content to reveal next | Left | Right |
| Logical next index | Increases | Increases |
The second row describes the slides' resting positions along the sequence, before navigation. The track movement describes how a later slide reaches the viewport. Mixing these two descriptions produces contradictory acceptance criteria such as “next must move left.”
This model suits the trail guide's reading sequence. A vertical carousel, a geographical panorama or a timeline with an established domain convention needs its own navigation contract. Do not infer its interaction solely from the language of its captions.
Keep the data array in the intended editorial order. Reversing the array changes the actual first item, saved index and analytics meaning. Adding row-reverse inside an RTL flex row also reverses the layout again. Set semantic direction on the component or an ancestor and let a normal row follow it. See RTL flexbox for the underlying layout behavior.
Repair the transform sign, not the content order#
Here is a small geometry fixture for the trail cards. It deliberately contains no links or navigation script, so changing its index isolates the movement problem from interaction handling.
<section class="trail-demo" dir="rtl" lang="ar" aria-labelledby="trail-heading"> <h2 id="trail-heading">اكتشف المسار الجيولوجي</h2> <div class="trail-window"> <div class="trail-track"> <article class="trail-card"><h3>بداية المسار</h3></article> <article class="trail-card"><h3>التكوينات الصخرية</h3></article> <article class="trail-card"><h3>نقطة الإطلالة</h3></article> </div> </div></section>These shared dimensions matter: the track's box is one viewport wide, while its nonshrinking children extend beyond it. There is no gap, padding or border in the distance calculation.
.trail-demo { min-inline-size: 0; }.trail-window { overflow: hidden; }.trail-track { display: flex; inline-size: 100%; --slide-index: 0;}.trail-card { flex: 0 0 100%; min-inline-size: 0; box-sizing: border-box;}Problem: an LTR animation applies a negative step in both languages.
.trail-track { transform: translateX(calc(var(--slide-index) * -100%));}At index zero, nothing moves, so the initial screenshot looks correct. At index one in RTL, the second card is already to the left of the viewport. Moving the track farther left takes it away from the window instead of into it.
Better: change the physical step while preserving the same index and dimensions.
.trail-track { --slide-step: -100%; transform: translateX(calc(var(--slide-index) * var(--slide-step)));}.trail-track:dir(rtl) { --slide-step: 100%;}Set the index in the console after loading the fixture:
document.querySelector('.trail-track') .style.setProperty('--slide-index', '1');The second card should fill the window in both directions. Change the section's dir to ltr and repeat with indices zero through two. The corrected rule preserves the original English position and movement.
These layout and selector behaviors were measured in Chromium 151; repeat the fixture in your supported browsers. CSS-only direction: rtl does not make :dir(rtl) match. Use an HTML dir attribute here; document direction versus CSS direction explains that distinction.
A percentage in MDN's translateX() reference refers to the transformed element's reference box. If the track becomes several viewport widths wide, a percentage step no longer equals one slide. Variable-width cards, gaps and grouped slides need measured snap positions, not this fixture's formula.
Do not copy this transform onto a library-managed track. It would compete with the library's positioning. Use the fixture to understand an existing custom implementation, or let the library own movement completely.
Match the library configuration to the HTML direction#
A translation engine can read the correct Arabic strings while the carousel engine retains its LTR default. Inspect the component's computed direction and its initialized library options separately. A direction attribute is not evidence that every JavaScript calculation has changed.
For example, Embla's version 8 options include a direction setting alongside the content's direction. Set both from the same locale state. This initialization fragment assumes embla-carousel version 8 is installed in a bundled application and the named elements already exist:
import EmblaCarousel from 'embla-carousel'; const root = document.querySelector('[data-trail-carousel]');const viewport = root.querySelector('[data-viewport]');const previous = root.querySelector('[data-previous]');const next = root.querySelector('[data-next]');const direction = root.matches(':dir(rtl)') ? 'rtl' : 'ltr';const reducedMotion = matchMedia('(prefers-reduced-motion: reduce)'); const carousel = EmblaCarousel(viewport, { direction, align: 'start', loop: false, slidesToScroll: 1}); function updateButtons() { previous.disabled = !carousel.canScrollPrev(); next.disabled = !carousel.canScrollNext();} previous.addEventListener('click', () => { carousel.scrollPrev(reducedMotion.matches);});next.addEventListener('click', () => { carousel.scrollNext(reducedMotion.matches);});carousel.on('select', updateButtons);carousel.on('reInit', updateButtons);updateButtons();Use the viewport, container and slide structure from Embla's required setup, with controls outside the draggable viewport. The fragment wires movement and endpoint states; the surrounding application still supplies labels, slide accessibility and its unmount cleanup.
The version 8 methods reference defines next and previous in terms of snap points. Keep those method assignments in Arabic. Swapping scrollNext() with scrollPrev() to compensate for an arrow graphic corrupts the control's meaning. The boolean argument requests an immediate jump when reduced motion is selected.
On a live locale change, update HTML direction and reinitialize the engine with the new direction. Preserve the selected content item by stable identity if translation also changes the available slides. Remove your own DOM listeners and destroy the instance when the component unmounts. Test the installed major version rather than mixing examples from different releases.
Native scrolling uses a different coordinate system#
A scrollable card strip can use native scrolling and CSS scroll snapping instead of a translated track. That is a different implementation, even if the result looks similar. Do not diagnose it by looking for an inline transform.
In an RTL scroll container whose content extends leftward, scrollLeft starts at zero at the right edge and becomes negative toward later content. A positive offset therefore cannot mean “next” in both languages. MDN documents the RTL scrollLeft behavior.
For a custom native strip, targeting the actual card can be clearer than accumulating a signed distance. This function accepts an existing slide element; it does not calculate the selected index:
function revealTrailCard(card) { card.scrollIntoView({ inline: 'start', block: 'nearest', behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'instant' : 'smooth' });}The scrollIntoView options provide logical inline alignment. However, this method can scroll ancestors as well as the strip. Test the page's vertical position, especially inside a dialog or nested scrolling panel. A carousel should not unexpectedly pull the whole page toward its heading.
Derive the settled selection from the implementation's snap or visibility logic. A requested target is not proof that scrolling finished there: the user may interrupt it. For native offsets, avoid exact equality comparisons against the end position because values can be fractional. Test overscroll behavior on your supported touch browsers before using raw offset arithmetic as an endpoint detector.
Give arrows a job and then draw them#
For the Arabic trail sequence, next points left and previous points right. Their labels describe the destination in the sequence, not a screen coordinate. Use wording equivalent to “Next stop,” rather than “Move left.” The latter becomes misleading if the component later switches orientation.
This markup fragment shows the Arabic controls for the library integration. The host supplies the shared root and viewport attributes used above:
<div class="trail-controls"> <button type="button" data-previous> <span class="trail-chevron trail-chevron--previous" aria-hidden="true" dir="ltr">‹</span> المحطة السابقة </button> <button type="button" data-next> المحطة التالية <span class="trail-chevron trail-chevron--next" aria-hidden="true" dir="ltr">›</span> </button></div>.trail-controls { display: flex; flex-wrap: wrap; gap: 0.75rem;}.trail-chevron { display: inline-block; }[data-trail-carousel]:dir(rtl) .trail-chevron { transform: scaleX(-1);}The glyph spans deliberately use LTR direction so that the explicit mirror controls their drawing. The ancestor selector reads the carousel's direction. Localize the visible labels for the English route. With icon-only controls, supply equally specific translated accessible names.
Do not mirror the entire button or carousel: that also flips text and other content. If the icon system already provides an RTL variant, remove the extra mirror. Check the final rendered arrow, including any pseudo-element supplied by a theme.
At a nonlooping endpoint, disable the action that cannot advance. At the first trail stop, previous is unavailable; at the last, next is unavailable. A disabled action must follow the logical sequence, not whichever button happens to occupy the left side.
Keep keyboard controls local to the carousel#
Native HTML buttons provide keyboard activation without a custom key handler. Test Tab through the trail controls, activate next with Enter and Space, and confirm that focus stays visible. A carousel containing content cards is not an ARIA range slider; adding role="slider" to the viewport gives it the wrong interaction model.
Arrow-key navigation is an additional design choice for a custom strip. If you provide spatial horizontal navigation, define Left Arrow as movement toward the left-positioned neighbor, which is next in this RTL sequence. Right Arrow goes toward the previous stop. Read direction from the relevant carousel, since an embedded component can differ from the page.
Scope the handler to the intended navigation surface. A text input inside a card still needs arrow keys to move its caret, and a nested select needs its own keyboard behavior. Do not intercept every arrow event bubbling through the document. Likewise, do not capture Tab to cycle through slides: visitors must be able to leave the carousel.
At endpoints, test what happens when the focused control becomes disabled. If the product preserves an unavailable control in the focus order with aria-disabled instead, its handler must also refuse activation. That attribute alone does not disable a button.
Test finger movement separately from screen-reader gestures#
For this RTL strip, start on the introduction, drag the content to the right and release past the engine's navigation threshold. The formations card should settle into view. Dragging left should return toward the introduction. A short drag may snap back; verify the settled index rather than treating any pointer movement as a completed navigation.
Calling this “swipe left to advance” would describe the wrong finger movement for the contract above. Teams also use “swipe direction” to mean the direction in which the next item lies. Write the acceptance test with a starting card, finger movement and resulting card so that the ambiguity disappears.
For a custom horizontal drag implementation, preserve vertical page scrolling and pinch zoom. MDN's touch-action reference explains how browser gesture handling interacts with pointer events. A setting such as pan-y pinch-zoom belongs to an implementation that handles horizontal dragging itself. Applying it to a native horizontal scroller can block the very browser gesture that scroller needs.
Test diagonal movement starting on a card, cancellation halfway through a drag, dragging across a link, and releasing outside the viewport. A cancelled gesture must not leave a stale pointer state or trigger the card's destination accidentally.
Provide tappable next and previous controls even when dragging works. W3C's Dragging Movements guidance distinguishes author-built dragging from native browser scrolling and requires an alternative to dragging where the criterion applies.
Screen-reader navigation gestures are a separate test. A one-finger gesture used to move accessibility focus is not evidence that the carousel's content drag works, and the component must not hijack it to force slide movement.
Decide what happens to offscreen content#
Clipping the track does not by itself make offscreen links unavailable to keyboard users. Before adding links to the trail cards, choose the component's accessibility model.
For a continuous strip treated as a collection of cards, let keyboard navigation reach the content and ensure that a focused card becomes visible. For a slideshow exposing only its current panel, keep inactive panels out of interaction and accessibility navigation. These models need different focus handling, especially when a wider viewport displays several cards.
The inert attribute removes a subtree from the tab order and accessibility tree without removing its layout box. That makes it an option for inactive transformed slides. It also prevents interaction with that content, so do not mark a visible, usable neighboring card inert just because it is not the selected index.
Never hide or make inert a slide that still contains focus without deliberately resolving that focus first. A timer should stop before it creates that situation. When a user activates next or previous outside the slide, keep focus on that control so they can activate it again. W3C's carousel functionality guidance covers this focus behavior and announcing the current item.
For a button-driven change, a short localized status can identify the new stop. Avoid announcing every intermediate drag position. Verify that visible focus remains inside the clipped viewport and that the next Tab destination is visible after each change.
Keep progress dots in the same sequence#
Render dot controls from the same ordered slide or snap model as the track. With a normal flex row inheriting RTL, the first dot appears at the right. Reversing that dot array as well makes the first visible dot select the last content item.
Dots need accessible names that identify what they select. The trail guide can name its stops rather than exposing a row of anonymous buttons. Mark the current picker consistently and test its announcement with the chosen semantics.
A group of buttons and a tablist are different patterns. Buttons retain their normal Tab stops. A tablist requires tab roles, associated panels, selection state and its own keyboard navigation. Do not add role="tab" merely to obtain a styling hook. The WAI-ARIA carousel pattern describes both approaches.
At wider breakpoints, one navigation step may move a group of cards. In that configuration, a dot may represent a snap point rather than an individual slide. Build the dot count from that navigation model and rebuild it when grouping changes. Otherwise the final dots can repeat a position or select an unreachable destination.
Make the current state visible without relying solely on color. Allow enough space around each dot for tapping. If the strip contains many stops, use a concise position indicator and next/previous controls instead of introducing a long row of tiny buttons.
Treat autoplay as a separate state machine#
Leave autoplay off for the trail guide. Its cards contain reading material, and manual navigation gives visitors time to examine each stop. Changing the interface to Arabic is not a reason to enable rotation or shorten the reading interval.
If a product requires autoplay, keep a user-controlled rotation state separate from the selected index. Include a visible start/stop control before the rotating content in keyboard order. Stop when focus enters the carousel and on pointer hover; after focus has stopped rotation, require an explicit request to restart. These behaviors follow the WAI-ARIA carousel pattern.
Do not restart just because a pointer leaves while a keyboard user remains inside. Track independent pause reasons so clearing one does not erase another. Stop timers on unmount, and define how returning to a backgrounded page behaves. Replaying accumulated timer ticks can skip the card the visitor was reading.
Honor reduced motion when deciding whether rotation starts, as well as when choosing a transition. Removing the animation duration while continuing to replace the content still leaves an automatically updating carousel. W3C's Pause, Stop, Hide explanation distinguishes auto-updating information from continuous movement; a short transition is not a substitute for control over updates.
Keep automatic changes quiet for assistive technology, and announce user-requested changes without stealing focus. Test the rotation control's label after every toggle. Its name should describe the action it will perform next, not the state it just left, as illustrated in W3C's carousel animation controls.
Exercise endpoints, resizing and loop boundaries#
Test the introduction, a middle stop and the viewpoint with buttons, dragging and direct selection. Record content identity alongside the index. A screenshot showing a highlighted dot is insufficient if that dot labels a different stop.
Resize while a later card is selected. Then load the Arabic font, expand the longest description and switch locale. Verify that the same content remains selected where it still exists, the measured snap positions update, and controls remain outside the clipped track. Avoid a fixed card height that cuts off the Arabic description merely to match the English screenshot.
If looping is enabled, test the last-to-first and first-to-last transitions independently. Libraries may reposition slides or maintain additional rendered copies. Do not use a rendered node's position as the content identity. Where copies exist, check duplicate IDs, repeated focus targets and announcements; do not assume every library implements loops by cloning.
Check a single stop and an empty result too. Hide redundant navigation when nothing can advance, and render an explicit empty state rather than an empty track with active arrows. If content filtering removes the selected stop, choose a documented replacement and refresh its status.
Finally, compare the track's bounds with the viewport and the document in both directions. Clipping neighboring slides inside the carousel is intentional; making the whole document scroll sideways is not. Test touch browsers directly, including diagonal gestures and overscroll, rather than treating desktop emulation as the final result.
For the transform fixture, this console inspection reports each card's physical position relative to the window:
const windowNode = document.querySelector('.trail-window');const trackNode = windowNode.querySelector('.trail-track');const windowBox = windowNode.getBoundingClientRect(); console.table([...trackNode.children].map((card, index) => { const box = card.getBoundingClientRect(); return { index, leftFromWindow: Math.round(box.left - windowBox.left), width: Math.round(box.width) };}));With a window width of 360px, no borders and index one, the corrected RTL fixture puts the second card at a relative left position of zero. Its first card sits to the right, at a positive window width. If the second card instead moves farther into negative coordinates, inspect the transform sign before changing the array or arrow labels. Run the measurement after any animation settles.
This separates a navigation failure from a content-height problem: the intended card may occupy the window correctly while its description is clipped vertically. Record both the settled geometry and the visible text. Also reload with JavaScript unavailable. The content should have a usable static presentation, with inactive controls hidden until enhancement succeeds, rather than leaving every stop after the introduction permanently clipped.
A free Ritla scan can check for a directional icon pointing against the sequence its control advances, , and for translateX moving an element off-screen in RTL, . For a failing track, continue with debugging RTL layout problems; for arrow decisions elsewhere in the interface, see what to mirror in RTL.