Skip to content

Svelte RTL: right-to-left layouts in Svelte

Set server-rendered direction in SvelteKit, keep locale changes reactive, and debug scoped styles, interpolated values and motion in RTL components.

By , Founder of Ritla

Guide13 min read

A SvelteKit page can load correctly in Arabic and then keep its old direction after a language change. The reverse failure is possible too: a browser effect fixes the interactive page while the server response still declares English direction. Testing only the final screenshot misses the distinction.

Svelte leaves direction to HTML and the application. Its reactivity can update a direction attribute, but scoped CSS does not convert physical properties, component props do not automatically become native attributes, and interpolated strings do not gain bidi isolation.

This guide uses a seed bank's germination-tray review screen. The component examples use Svelte 5 runes. The SvelteKit example assumes server rendering and locale-prefixed routes beneath src/routes/[locale], with supported locales ar and en. It uses JavaScript so the direction mechanism stays visible without framework type-import differences between major versions.

Decide which layer owns direction#

Separate the values before changing styles:

LayerResponsibilityEvidence to inspect
DocumentPage language and base directionInitial HTML and current root attributes
Route localeWhich supported language was requestedMatched route parameter and returned layout data
Svelte componentReactive attributes and direction-dependent behaviorCurrent props and rendered native elements
CSSSpacing, alignment and physical exceptionsWinning declarations and computed values
ContentTranslated text and isolated technical valuesVisible messages and accessible names

For an Arabic document, the root declaration is lang="ar" dir="rtl". Language identifies the text's language; it does not select direction. The W3C structural direction guidance explains why these are separate declarations.

A nested RTL wrapper can be appropriate for an Arabic preview inside an English application. It is insufficient as the only direction declaration for a wholly Arabic document. R001 covers document direction missing, contradicted, or declared only in CSS.

Give one application boundary responsibility for root attributes. If an internationalization integration already supplies them, extend that integration. Independent effects in the page, header and language picker can overwrite one another as components mount or disappear.

For a plain Svelte application, set the initial attributes in the host document and update them through the application's language owner when switching. A reusable tray component should inherit direction or accept a local direction prop. It should not change the entire document when mounted in a preview, dialog or component test.

Render SvelteKit root attributes in the response#

An onMount callback cannot establish server-rendered direction. Svelte documents that onMount does not run on the server. The same limitation applies to $effect: it is a browser-side mechanism.

For this URL-based application, the route parameter is the locale authority. Browser language or an old preference must not silently turn a requested Arabic route into an English document.

Define the supported choices once:

js
// src/lib/locale.jsexport function isLocale(value) {  return value === 'ar' || value === 'en';} export function localeSettings(value) {  return value === 'ar'    ? { lang: 'ar', dir: 'rtl' }    : { lang: 'en', dir: 'ltr' };}

Use application-owned placeholders in the existing page template:

html
<!-- src/app.html --><!doctype html><html lang="%ritla.lang%" dir="%ritla.dir%">  <head>    <meta charset="utf-8" />    <meta name="viewport" content="width=device-width, initial-scale=1" />    %sveltekit.head%  </head>  <body>    <div style="display: contents">%sveltekit.body%</div>  </body></html>

Keep the project's other head content, security configuration and existing template attributes when integrating this fragment. SvelteKit's project-structure documentation describes the page template and framework placeholders. The two prefixed placeholders above are supplied by this application, not built-in SvelteKit substitutions.

Replace them through the existing server handle hook:

js
// src/hooks.server.jsimport { isLocale, localeSettings } from './lib/locale.js'; export async function handle({ event, resolve }) {  const locale = isLocale(event.params.locale) ? event.params.locale : 'en';  const settings = localeSettings(locale);   return resolve(event, {    transformPageChunk: ({ html }) => html      .replace('%ritla.lang%', settings.lang)      .replace('%ritla.dir%', settings.dir)  });}

The hooks documentation describes response HTML transformation. This transform changes known template tokens using values from a closed mapping. Do not inject an unchecked URL segment into an HTML attribute or use a broad replacement that might also change page content.

Merge this behavior with existing hooks rather than replacing authentication or other request handling. The English fallback here applies outside recognized locale routes; it does not make unsupported locale URLs valid. The localized layout below rejects those.

Inspect the actual response for a direct Arabic request. The placeholders must be gone, and both root attributes must already be correct before JavaScript runs. Do not parse each streamed chunk as a complete HTML document: the hooks API explicitly allows chunks that are not independently well formed.

Keep document attributes current during navigation#

The server transform handles an HTML response. Client-side navigation also needs the current document attributes to follow the new locale.

Return the same locale choice from the localized layout's load function:

js
// src/routes/[locale]/+layout.server.jsimport { error } from '@sveltejs/kit';import { isLocale, localeSettings } from '../../lib/locale.js'; export function load({ params }) {  if (!isLocale(params.locale)) {    error(404, 'Unsupported language');  }   return { locale: params.locale, ...localeSettings(params.locale) };}

Put actual pages beneath that layout, such as src/routes/[locale]/trays/+page.svelte. The routing guide explains this relationship, and the load documentation explains how returned layout data reaches its components.

The layout uses that data both in server-rendered markup and in a browser effect:

svelte
<!-- src/routes/[locale]/+layout.svelte --><script>  let { data, children } = $props();   $effect(() => {    document.documentElement.lang = data.lang;    document.documentElement.dir = data.dir;  });</script> <div lang={data.lang} dir={data.dir}>  {@render children()}</div>

The wrapper receives direction during rendering; the effect updates the external document node in the browser. It complements the response transform rather than replacing it. Avoid deriving application state inside this effect: the route data already supplies that state.

Keep head metadata in its own mechanism. Svelte's head element renders titles and other head content; it is not an API for assigning attributes to the document root. A translated title and an RTL body wrapper can therefore coexist with stale root attributes. Inspect all three rather than treating a successful title update as proof that the language switch completed.

This layout owns attributes for the localized application subtree. If the product also has nonlocalized application routes, put attribute ownership at a boundary that covers those routes too, with an explicit fallback there. Otherwise leaving the localized subtree can leave the previous language on the document.

Test navigation from Arabic to English and back without a full reload. Check the root attribute after each destination renders, then use Back and Forward. Also repeat with direct loads, because a working effect says nothing about the initial response.

Avoid snapshots in reused layouts and components#

This looks plausible inside a layout script, but only records an initial value:

js
// Problem: data is the reactive layout prop from $props().const direction = data.dir;

SvelteKit can preserve layout and page instances during navigation. Setup code does not become reactive merely because its input once came from a prop. Use data.dir at the point of use, as the layout does above, or derive a reactive alias:

js
// In the same layout script:let direction = $derived(data.dir);

Svelte's $derived documentation describes dependency tracking. Derive other locale-dependent objects, such as a formatter or translated action list, from their current inputs too. Do not fix a stale value by wrapping the entire application in a locale-keyed block unless destroying its state is actually the intended switching behavior.

Preserving the tray selection and an unfinished review note is useful. Recreating every component to refresh direction can discard both. Test a switch with that state present, and make any intentional reset visible in the product's requirements.

Keep request-specific language out of a mutable module-level store on the server. An imported constant mapping is fine; a shared variable holding the current user's locale is a different design. SvelteKit's state-management guidance covers shared server state and preserved component instances. Return request data or create state in the relevant component tree instead.

Update messages and formatters from the same locale input#

Changing dir does not translate a button or recreate a number formatter. A summary can move to the right while retaining the English wording and formatting captured during its first render.

This component derives both outputs from its current locale prop. The seed count stays unchanged during a language switch, making it a useful diagnostic fixture:

svelte
<!-- GerminationSummary.svelte --><script>  let { locale = 'ar', seedCount = 276 } = $props();  let heading = $derived(locale === 'ar' ? 'البذور المنبتة' : 'Germinated seeds');  let direction = $derived(locale === 'ar' ? 'rtl' : 'ltr');  let number = $derived(new Intl.NumberFormat(locale, {    numberingSystem: 'latn',    maximumFractionDigits: 0  }));</script> <p lang={locale} dir={direction}>{heading}: {number.format(seedCount)}</p>

Pass the layout's data.locale to this component. Its two-language mapping assumes the validated locale contract above. The explicit numbering system is this seed bank's chosen digit policy, not a requirement for Arabic interfaces. MDN's Intl.NumberFormat reference documents the formatting API.

For a larger application, use the existing translation system rather than expanding conditional dictionaries across components. Include disabled-state explanations, empty trays, review failures and accessible control names in that system. A page heading changing language does not establish that those less visible messages follow it.

Test locale changes while the count stays fixed, then count changes while the locale stays fixed. Those interactions exercise different dependencies. Compare the server-rendered summary with the browser result too; an implicit machine locale or separately configured formatter can create a mismatch even when both renderers receive the same count.

Make scoped styles logical before adding overrides#

Suppose the tray review card reserves extra space at reading end for its status area. The existing LTR component stylesheet contains:

css
/* Problem: physical sides in TrayReview.svelte. */.tray {  padding: 16px 38px 16px 26px;  text-align: left;}

Scoping does not change what those declarations mean. The larger inset stays on the physical right even when the document becomes RTL. Express the same LTR geometry with logical properties:

css
.tray {  padding-block: 16px;  padding-inline: 26px 38px;  text-align: start;}

In horizontal English layout, left padding remains the start value and right padding remains the end value. RTL exchanges their physical mapping. The CSS logical-properties specification defines these relationships. R030 covers direction-sensitive physical properties without an RTL override.

Check both languages after the change. A conversion that moves the card's status area in English changed the original design instead of making its existing relationship direction-aware. Keep intentional physical coordinates, such as positions on a photographed seed tray, attached to that image's coordinate system.

Svelte's scoped-style documentation explains the generated scope class and its specificity effect. When a global RTL rule loses to component CSS, inspect the winning declaration. Loading another global stylesheet later is not evidence that it wins the cascade. Prefer repairing the component's source over accumulating increasingly specific exceptions.

Also inspect inline style directives and styles supplied by dependencies. A logical declaration in one stylesheet cannot establish that a later physical shorthand or an inline binding leaves the intended spacing intact.

Keep the tray records in their intended reading sequence. An RTL flex row already changes which physical edge contains the first item; reversing the array as well changes the data sequence. Decide whether the first tray means earliest inspection, highest priority or another product-defined order, and keep that meaning stable across languages.

Where tray components hold local state and the list can change, use a stable record identifier in a keyed each block, such as {#each trays as tray (tray.id)} for a supplied trays collection. That preserves the relationship between a component and its record as items move. It does not fix direction or make a deliberately reversed list semantically correct.

Test a language switch with the middle tray selected, then insert a new tray before it. Confirm that the selection and unfinished note still belong to the same record. Tab through the controls and compare their order with the intended reading sequence. This catches identity and ordering mistakes that a two-card static screenshot cannot reveal.

Match inherited direction without scoping away the ancestor#

Some assets need a direction-specific exception. In a component stylesheet, this selector targets an external document ancestor as if it belonged to the component:

css
/* Problem: html is outside this component's scoped markup. */html[dir="rtl"] .sequence-arrow {  transform: scaleX(-1);}

For a selector intentionally tied to the document, mark only the ancestor global:

css
:global(html[dir="rtl"]) .sequence-arrow {  transform: scaleX(-1);}

Svelte's global-style documentation describes this escape from scoping. The arrow selector remains local; the document selector does not.

For a reusable component that can live inside nested direction regions, consider .sequence-arrow:dir(rtl) instead. MDN's :dir() reference distinguishes semantic direction from merely looking for an attribute on that particular element. This also avoids tying the component to the document when a local English preview sits inside the Arabic page.

Use the exception only for an asset whose action should mirror. Do not apply it to seed photographs, logos or the entire card. A semantic direction selector does not prove that an icon means the right thing; verify its action against what should be mirrored in RTL.

Forward component direction to the element that needs it#

Passing dir to a Svelte component passes a prop. It does not guarantee a native element receives that attribute. A wrapper component must implement the contract.

This review-region component explicitly forwards its direction:

svelte
<!-- ReviewRegion.svelte --><script>  let { dir = 'rtl', children } = $props();</script> <section {dir}>  {@render children()}</section>

The default makes this an Arabic review region; omit the attribute instead if the component's contract is to inherit all direction from its parent. A reusable wrapper may also forward selected native attributes or rest props, as described in the $props documentation. Be deliberate about which element owns them when a component renders several siblings.

Apply the same inspection to a custom input wrapper. Direction for an editable value belongs on its native input or textarea, while labels and help text can remain Arabic. A component-level dir prop that is never forwarded cannot fix that field. See Arabic text input direction for the content-specific decision.

For third-party popups, inspect where the library renders them. Content moved beneath the document body no longer inherits from the opener's local DOM ancestor. Use the library's supported direction or container option and test the actual popup, including keyboard behavior. Do not assume Svelte context and DOM inheritance are interchangeable: they describe different relationships.

Isolate interpolated identifiers without rebuilding messages as HTML#

Svelte interpolation escapes text, but escaping and bidi isolation solve different problems. This seed-lot reference begins with digits and ends with Latin letters:

svelte
<script>  const lotReference = '392681-GR';</script> <!-- Problem: no boundary around the technical value. --><p dir="rtl">مرجع دفعة الإنبات: {lotReference}</p>

For this shape after Arabic text, the behavior checked in Chromium 151 puts the letter group before the digit group. The identifier must retain its defined sequence. Add the boundary in the template:

svelte
<script>  const lotReference = '392681-GR';</script> <p dir="rtl">مرجع دفعة الإنبات: <bdi dir="ltr">{lotReference}</bdi></p>

The W3C inline bidi guidance explains isolating inserted runs. R021 covers unisolated bidi hazards: phones, emails, Latin tokens inside Arabic text.

Keep the value as an ordinary expression inside the isolating element. Svelte's basic-markup documentation explains that expressions are escaped. Replacing interpolation with {@html} is unnecessary for direction and changes how content is interpreted. Let the translation integration preserve markup boundaries without assembling an unchecked HTML string.

This fixed-direction example is for a known technical identifier. A participant's free-text observation has a different content contract and may need automatic direction around the observation alone. Do not put the Arabic label inside the same automatic-direction boundary. Use Arabic and English mixed text for that decision rather than forcing every interpolated value LTR.

Treat transition offsets as physical coordinates#

Svelte's fly transition accepts physical horizontal and vertical offsets. A positive horizontal offset does not become negative because an ancestor is RTL. Its transition API documents those position parameters.

If the tray detail should enter from reading start, derive the offset from direction. This small Arabic fixture accepts direction independently so it can be exercised in both contexts:

svelte
<script>  import { fly } from 'svelte/transition';   let { direction = 'rtl' } = $props();  let expanded = $state(false);  let entryX = $derived(direction === 'rtl' ? 44 : -44);</script> <section dir={direction}>  <button type="button" onclick={() => expanded = !expanded} aria-expanded={expanded}>    تفاصيل صينية الإنبات  </button>  {#if expanded}    <p in:fly={{ x: entryX, duration: 180 }}>الصينية جاهزة لمراجعة نسبة الإنبات.</p>  {/if}</section>

Translate the fixture's messages when integrating it into the bilingual product. The direction argument governs the motion policy, not translation. Preserve the English offset when adding its RTL counterpart, and check the start of the animation rather than only its final frame.

An incoming offset is sampled for a transition; do not promise that changing language midway through an animation retargets it as a new entrance. Decide whether switching waits for motion, closes the detail, or leaves the existing transition to finish. Respect the application's reduced-motion preference too. If movement has no directional meaning, a fade can avoid an unnecessary direction branch.

Check how that preference reaches Svelte transitions. The transition accessibility guidance explains that a global CSS rule reducing animation duration does not disable transitions driven by the Web Animations API. Adjust the transition's parameters through the supported motion preference API or the application's existing equivalent. Verify the reduced-motion case directly instead of assuming a global stylesheet has covered it.

Test the motion near the viewport edge and at narrow widths. A correct final position does not establish that the intermediate frame avoids clipping or document overflow. The same review applies to custom actions and third-party animation code that calculate horizontal distances outside Svelte's template.

Verify the response, the switch and the preserved state#

Keep one seed lot selected throughout the test so a data change cannot conceal a direction update. Start on the Arabic tray route in a fresh session, switch to English through application navigation, then return using both the selector and browser history.

TestWhat it establishes
Inspect direct-response HTML with scripts disabledRoot language and direction exist before browser effects
Navigate between locale routes without reloadingExisting layout data and document attributes update
Keep a note and selection during switchingDirection changes do not depend on unintended remounting
Render the card beneath LTR and RTL parentsLocal CSS respects inherited direction
Open a popup from a nested direction regionPopup placement and direction follow its actual contract
Exercise narrow layouts and motionLong Arabic text and intermediate frames fit

Svelte's testing guide describes component and browser testing approaches. Use component assertions for native attributes and translated accessible names. Use a real browser for text display, wrapping, focus and geometry. A DOM-only test environment cannot establish what the tray card looks like.

After changing component state in a low-level test, await the relevant update. Svelte's tick API resolves after pending state changes are applied; it does not certify that a network request, font download or animation has finished. Wait for the specific application state before measuring those outcomes.

Use a long tray description and a failed review response as separate fixtures. The first exercises wrapping; the second exposes messages that may not be rendered until after switching. With focus inside the review region, verify that a label update leaves focus on the intended control. If the implementation replaces that control, check where focus goes afterward. These are interaction checks, not consequences that follow automatically from a correct root dir.

Repeat direct loads against the production deployment. Prerendered pages need their locale-specific HTML generated at build time; a browser preference cannot customize an already-generated file. SvelteKit's page-options documentation explains prerendering and SSR choices. If SSR is disabled, document that limitation rather than presenting a client effect as server-rendered support.

Inspect unsupported paths and error responses as well. They can bypass the localized layout, so verify that fallback language, direction and message text agree. When the response is right but navigation is wrong, examine reactive inputs and attribute ownership. When navigation is right but a fresh load is wrong, inspect the response transform and deployed HTML first.

A free Ritla scan of the Arabic tray screen can surface document direction missing, contradicted, or declared only in CSS, and direction-sensitive physical properties without an RTL override. Continue with dynamic text direction for editable observations, or Arabic text overflow when the component updates direction correctly but its translated content no longer fits.

Checks in this guide

See what your Arabic pages are hiding

Paste a URL. Ritla renders the page on desktop and mobile, runs every check, and shows the top issues with screenshot evidence.

Scan a page freeBrowse the checks