Sub topic 12
Supporting right-to-left languages
This chapter assumes you have a working react-i18next setup, a language switcher that updates lang and dir on the html element (from the previous chapters), and basic CSS layout knowledge with flexbox. By the end you will be able to make a layout work in both reading directions without writing a second stylesheet.
What right-to-left changes
Arabic, Hebrew, Persian and Urdu are written right to left (RTL). Switching dir to rtl makes the browser change several things on its own:
- Text starts at the right edge of its container.
- Inline content, such as a row of buttons in a flex container, flows from right to left.
- Table columns and grid columns are laid out starting from the right.
- Scrollbars and
text-align: startmove to the other side.
The browser does not change anything you hard-coded with physical directions: margin-left, padding-right, left: 0, text-align: left, border-right, float: left. Those stay on the physical side, so your layout ends up half mirrored. This is the main source of RTL bugs.
Set the direction at the root
The direction belongs on the html element, so it applies to the whole document. The language switcher from the earlier chapter already does this with i18n.dir(code). For code that must also run on first load, put the same logic in a hook:
import { useEffect } from 'react';
import { useTranslation } from 'react-i18next';
export function useDocumentDirection() {
const { i18n } = useTranslation();
const language = i18n.resolvedLanguage ?? 'en';
useEffect(() => {
document.documentElement.lang = language;
document.documentElement.dir = i18n.dir(language);
}, [language, i18n]);
}Call useDocumentDirection() once, near the root of your app. i18n.dir() returns 'rtl' or 'ltr' based on the language code, so you do not need your own list of RTL languages.
Use logical properties
CSS logical properties describe layout relative to the writing direction instead of the screen. "Start" is the side where text begins, and "end" is the opposite side. In LTR, start is left. In RTL, start is right.
| Physical (avoid) | Logical (use) |
|---|---|
| `margin-left` | `margin-inline-start` |
| `margin-right` | `margin-inline-end` |
| `padding-left` / `padding-right` | `padding-inline-start` / `padding-inline-end` |
| `left: 0` | `inset-inline-start: 0` |
| `right: 0` | `inset-inline-end: 0` |
| `text-align: left` | `text-align: start` |
| `border-left` | `border-inline-start` |
| `float: left` | `float: inline-start` |
| `border-top-left-radius` | `border-start-start-radius` |
Vertical properties such as margin-top do not change for the languages in this chapter. You can leave them alone, or use margin-block-start if you want consistency.
The stylesheet below works in both directions without any [dir="rtl"] overrides:
.card {
padding-inline: 1rem;
margin-inline-start: 2rem;
border-inline-start: 4px solid currentColor;
text-align: start;
}In LTR the accent border and the indent are on the left. In RTL both are on the right.
A few more patterns that come up often:
.badge {
position: absolute;
inset-block-start: 0.5rem;
inset-inline-end: 0.5rem;
}
.tab {
border-start-start-radius: 8px;
border-end-start-radius: 8px;
}
.input-with-icon {
padding-inline-start: 2.5rem;
}inset-inline-end places the badge in the top-right corner for English and the top-left corner for Arabic. The two border-*-start-radius values round the start side of a tab.
What the browser mirrors for you
Several layout tools follow dir without extra work, as long as you do not override them with physical values:
- Flexbox.
flex-direction: rowplaces the first item at the start edge, andjustify-content: flex-startaligns to the start. A navigation bar flips by itself. - Grid. Column 1 sits at the start edge.
- Inline text and inline-block elements. They flow from the start edge.
- Form controls. Text inputs, checkboxes and selects adopt the direction.
Do not use row-reverse as a manual flip. In RTL it would undo the browser's own mirroring and put your items back in LTR order.
What you must handle yourself
Directional icons and images
Arrows, back buttons, "next" chevrons and progress indicators carry meaning from direction. A "back" arrow that points left in English should point right in Arabic. Flip these with the :dir() pseudo-class:
.icon-directional:dir(rtl) {
transform: scaleX(-1);
}If you need to support browsers without :dir(), use the attribute selector instead: [dir="rtl"] .icon-directional. Only flip icons that express direction. Do not flip a clock face, a checkmark, a logo, a play button or a photograph. Media controls conventionally keep their orientation, and text inside images cannot be mirrored.
Embedded left-to-right content
Arabic and Hebrew text often contains LTR fragments: brand names, product codes, email addresses, user names written in Latin script. The Unicode bidirectional algorithm (bidi) decides how mixed text is ordered. Punctuation next to an LTR fragment can end up on the wrong side.
When you render a value you do not control, wrap it in bdi, which isolates it from the surrounding text:
import { useTranslation } from 'react-i18next';
export function Greeting({ userName }: { userName: string }) {
const { t } = useTranslation();
return (
<p>
{t('welcome_prefix')} <bdi>{userName}</bdi>
</p>
);
}For a text field where users may type in either direction, set dir="auto" on the input. The browser picks the direction from the first strong character typed.
Numbers, dates and formatting
You already use Intl for formatting. Remember that the output follows the locale, including digits. new Intl.NumberFormat('ar-EG').format(1234.5) produces Arabic-Indic digits (١٬٢٣٤٫٥). Whether that is what your users want is a product decision. If you prefer Western digits, request them with the -u-nu-latn extension: 'ar-EG-u-nu-latn'. Keep the choice consistent across the app, including inputs and charts.
Animations and transforms
transform: translateX(10px) and left in keyframes are physical. A slide-in drawer that enters from the left in English should enter from the right in Arabic. Either use a custom property that you flip under :dir(rtl), or use inset-inline-start where you can animate it:
.drawer {
--slide: -100%;
transform: translateX(var(--slide));
}
.drawer:dir(rtl) {
--slide: 100%;
}
.drawer.open {
transform: translateX(0);
}Common errors
- Layout is mirrored except one component. Search for
left,right,margin-left,padding-rightandtext-align: leftin that component's CSS. Third-party CSS and CSS-in-JS snippets are frequent sources. - Everything is right-aligned but the sidebar is still on the left. The sidebar probably uses
float: leftorposition: absolute; left: 0. - Punctuation jumps to the wrong end of a sentence. An LTR fragment is interfering with the bidi algorithm. Wrap the dynamic value in
bdi. - Modals ignore the direction.
diris set on a wrapper and not onhtml. - Back arrows point the wrong way. The icon is not flipped. Add a directional class.
- Shadows and gradients look lopsided.
box-shadow: 4px 0 ...andlinear-gradient(to right, ...)are physical. Use a custom property that flips under:dir(rtl), orto inline-endis not valid in gradients, so a flipped variable is the practical choice.
Testing the direction
A unit test can check that switching to an RTL language updates the document:
import { render } from '@testing-library/react';
import { I18nextProvider } from 'react-i18next';
import i18n from './i18n';
import { useDocumentDirection } from './useDocumentDirection';
function Probe() {
useDocumentDirection();
return null;
}
test('sets dir to rtl for Arabic', async () => {
await i18n.changeLanguage('ar');
render(
<I18nextProvider i18n={i18n}>
<Probe />
</I18nextProvider>
);
expect(document.documentElement.dir).toBe('rtl');
expect(document.documentElement.lang).toBe('ar');
});For this test to pass, i18n.ts must include an ar resource (or have it loaded) so that resolvedLanguage becomes ar.
Exercise
A card has margin-left: 2rem; border-right: 4px solid red; text-align: left; and a "back" arrow icon. Rewrite the CSS so it works in both LTR and RTL, and say what else you must do for the icon.
Show answer
Use margin-inline-start: 2rem; border-inline-end: 4px solid red; text-align: start;. For the arrow, add a class such as .icon-directional and flip it with .icon-directional:dir(rtl) { transform: scaleX(-1); } (or [dir="rtl"] .icon-directional for older browsers), because the icon's meaning depends on reading direction. Also confirm that dir is set on the html element so the logical properties resolve correctly.
Exercise
Why is flex-direction: row-reverse a poor way to support RTL?
Show answer
Flexbox already places items starting from the inline-start edge, so row mirrors automatically when dir is rtl. row-reverse reverses that, so the items would appear in LTR order in RTL documents, and you would have to reverse it again for LTR. Rely on the default direction instead.