Right-to-left and logical properties
Make web components work right to left with CSS logical properties like margin-inline-start, the :dir() selector in shadow DOM, and icons that flip.
- 01Write CSS that works in both directionsUse logical properties like
margin-inline-startandinset-inline-end, so start and end follow the page's direction. - 02Know which way a component runsStyle it with
:host(:dir(rtl)), and tell wheredirreaches inside a shadow root and where slotted content takes it from. - 03Flip only the icons that pointMirror arrows that point along the line of text, and leave cups, clocks, check marks, and play buttons as they are.
How do you make a web component work right to left?
Mariam is a regular at Leaf and Kettle. She reads Arabic, so she translates the shop's menu. Arabic is written from right to left. Ravi marks the page that way, and most of it turns around by itself. The words start on the right. Rows of buttons start on the right.
Two things look wrong. When Mariam adds a tea, the steam rises over the first letter of its name. And the Add milk switch is on, but its thumb pokes out of its track. Why did these two parts stay behind, and how do you fix them for good?
Write a component's CSS with logical properties, like margin-inline-start instead of margin-left. They name the start and end of a line, so they follow the page's direction. For anything else that must change, use :host(:dir(rtl)). And flip an icon only when it points along the line.
Here is Mariam's menu, with the kit as lesson 15.1 left it:
<link rel="stylesheet" href="tea-kit/tokens.css"><div dir="rtl" lang="ar"> <tea-card><span slot="name">شاي أخضر</span></tea-card> <tea-toggle checked>مع حليب</tea-toggle></div><script type="module"> import "./tea-kit/index.js";</script>- Line 1 links the kit's tokens, the values every component shares.
- Line 2 sets the direction with
dir="rtl"and the language withlang="ar". Everything inside runs right to left. - Line 3 is the tea card. Its name says green tea in Arabic.
- Line 4 is the switch. Its label says with milk, and it starts on.
Press Add on the card. The steam appears at the top right corner, right where the Arabic name begins. Then look at the switch: its round thumb sits past the right end of its track. The course's test measures both in Chrome.
The rest of the card mirrored on its own. The name moved to the right, and the quantity buttons and Add swapped sides. Why it matters: text and rows follow the direction for free, but anything the CSS pins to the left or the right stays put.
Leaf and Kettle opens a second shop. Its room is a mirror image of the first: the door is on the right. Ravi's setup notes say "menu board on the left wall", so in the new shop, the board ends up far from the door. The notes should have said "by the door". That works in both rooms.
- In real life: "Put the menu board on the left wall"
- In JavaScript:
margin-left, a physical property - In real life: "Put the menu board by the door"
- In JavaScript:
margin-inline-start, a logical property - In real life: The second shop, built as a mirror image
- In JavaScript: A page with
dir="rtl"
Say start and end, not left and right. Logical properties follow the direction of the text. :host(:dir(rtl)) styles what logical properties can't say. And only icons that point along a line flip.
What are CSS logical properties?
Most CSS you know is physical. margin-left, right, and width are tied to the screen: left is always left, and width is always across. They mean the same thing on every page, in every language.
Logical properties name the flow of the text instead. MDN describes two directions:
- The inline direction is the way a line of text runs. In English and in Arabic, it runs sideways.
- The block direction is the way paragraphs stack. In English and in Arabic, they stack downward.
Each direction has a start and an end. In English, a line starts on the left. In Arabic, it starts on the right. So margin-inline-start is the margin where lines start. It's the left margin in English and the right margin in Arabic.
Try it. This page has one paragraph of each kind. Pick a direction:
<style> p { border: 2px solid seagreen; } .physical { margin-left: 24px; } .logical { margin-inline-start: 24px; }</style><div dir="ltr"> <p class="physical">margin-left</p> <p class="logical">margin-inline-start</p></div><script> for (const p of document.querySelectorAll("p")) { const style = getComputedStyle(p); console.log(`${p.className}: left ${style.marginLeft}, right ${style.marginRight}`); }</script>In English, the start of a line is its left end. So margin-inline-start is the left margin, the same as margin-left.
- Line 3 gives the first paragraph a 24px left margin.
- Line 4 gives the second a 24px margin at the start of the line.
- Line 6 sets the box's direction. The playground changes it.
- Line 13 prints each paragraph's margins, read with
getComputedStyle().
- With
dir="ltr", both printleft 24px, right 0px. - With
dir="rtl", the physical one still printsleft 24px, right 0px. The logical one printslogical: left 0px, right 24px.
margin-inline-start puts its 24px at the start, so it moves to the right in the rtl window. margin-left stays on the left in both.Notice what getComputedStyle() said. A logical property isn't a new kind of margin. The browser turns it into a physical one, using the element's direction. MDN says the same: it maps to a physical margin by the writing mode, the direction, and the text orientation.
Every physical side has a logical name. MDN's guide lists them all. Here are the ones a component uses most. Read each row across:
| If you wrote | Write instead | What it means on a right-to-left page |
|---|---|---|
margin-left | margin-inline-start | The right margin, where each line starts. |
padding-right | padding-inline-end | The left padding, where each line ends. |
padding-left and padding-right | padding-inline: 12px 24px | 12px on the right and 24px on the left: start first, then end. |
border-left | border-inline-start | The border on the right. |
right: 8px | inset-inline-end: 8px | 8px from the left edge. |
border-top-left-radius | border-start-start-radius | The top right corner. |
text-align: left | text-align: start | The words line up on the right. |
width and height | inline-size and block-size | Still the width and the height. Arabic lines run sideways too. |
margin-top | margin-block-start | Still the top margin. Paragraphs stack downward in Arabic too. |
Sizes stay the same in Arabic. A line still runs sideways, so inline-size is the width. It only turns into the height in a vertical writing mode, like vertical Japanese, as MDN's sizing guide explains.
Why it matters: one logical rule works in both directions. You never write a second rule for right-to-left pages.
How do you write component CSS for both directions?
Ravi tries it on a small new component, tea-note: a tasting note in a bubble. Its sheet uses only logical names. Here it is, in the tea-note.js tab:
const sheet = new CSSStyleSheet();
sheet.replaceSync(`
:host { display: block; position: relative; inline-size: 220px; margin-block-end: 8px; }
p { margin: 0; padding-inline: 12px 24px; border-inline-start: 4px solid seagreen; text-align: start; }
p { border-radius: 12px; border-start-start-radius: 0; background: honeydew; }
.new { position: absolute; inset-block-start: 6px; inset-inline-end: 6px; inline-size: 8px; block-size: 8px; border-radius: 50%; background: seagreen; }
`);
customElements.define("tea-note", class extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" }).innerHTML = `<p><slot></slot></p><span class="new"></span>`;
this.shadowRoot.adoptedStyleSheets = [sheet];
}
});- Line 3 sets the note's width with
inline-size, and its space below withmargin-block-end. - Line 4 uses
padding-inline: 12px 24px. The first value is for the start, the second for the end. Then a green bar withborder-inline-start.text-align: startlines the words up where each line begins. - Line 5 rounds every corner, then makes one square with
border-start-start-radius: 0. That's the corner where the block starts and the line starts: the top corner on the start side. - Line 6 places a small dot with
inset-block-startandinset-inline-end: 6px from the top, and 6px from the end of the line.
Now the same note in both directions. The script reads back where each part ended up:
<div dir="ltr"><tea-note>Fresh and grassy.</tea-note></div><div dir="rtl"><tea-note>طازج وعشبي.</tea-note></div><script src="tea-note.js"></script><script> for (const note of document.querySelectorAll("tea-note")) { const host = note.getBoundingClientRect(); const p = getComputedStyle(note.shadowRoot.querySelector("p")); const dot = note.shadowRoot.querySelector(".new").getBoundingClientRect(); const bar = p.borderLeftWidth === "4px" ? "left" : "right"; const corner = p.borderTopLeftRadius === "0px" ? "left" : "right"; const near = host.right - dot.right === 6 ? "right" : "left"; console.log(`${note.parentElement.dir}: ${host.width}px wide, bar on the ${bar}, square corner top ${corner}, dot top ${near}`); }</script>- Line 1 is the note in English. Line 2 is the same note in Arabic, in a right-to-left box.
- Lines 6 to 8 read the host's box, the bubble's computed styles, and the dot's box.
- Lines 9 to 11 turn the physical values into words: which side has the bar, the square corner, and the dot.
- Line 12 prints one line per note.
ltr: 220px wide, bar on the left, square corner top left, dot top rightrtl: 220px wide, bar on the right, square corner top right, dot top left
Every part moved to the other side, and the width stayed 220px. The component did it alone. The page only said dir="rtl".
Some CSS doesn't need logical names:
- Shorthands with the same left and right, like
padding: 4px 12px. Both sides are equal, so swapping them changes nothing. - Things that move up or down for a real reason. The card's steam rises with
translateon the y axis, as lesson 12.7 wrote it. Steam goes up in every language.
Some properties have no logical form. translate is one: translate: 16px 0 always moves right. For those, the component has to know its direction. That's the next section.
Why it matters: a component can't see the page it lands on. Logical names let it fit either direction without asking.
What does the :dir() selector do?
First, where does a direction come from? From the dir attribute. It takes three values:
ltr: left to right, like English.rtl: right to left, like Arabic, Hebrew, Persian, or Urdu.auto: the browser decides from the text inside.
An element with no dir takes its parent's direction. With no direction anywhere, a page runs left to right. A page in Arabic puts dir="rtl" on its <html> tag. Use the attribute, not the CSS direction property. Lesson 14.2 showed why: CSS alone doesn't change what selectors see.
The :dir() selector matches an element by the direction it has. :dir(rtl) matches every element that runs right to left, whether it set dir itself or got it from a parent. MDN warns that [dir="rtl"] is different. An attribute selector only finds elements that carry the attribute.
In a component, that's :host(:dir(rtl)) against :host([dir="rtl"]). This sign has one rule of each kind, in the tea-sign.js tab:
const sheet = new CSSStyleSheet();
sheet.replaceSync(`
:host { display: block; padding: 4px 8px; border: 2px solid silver; }
:host([dir="rtl"]) { border-color: crimson; }
:host(:dir(rtl)) { background: honeydew; }
`);
customElements.define("tea-sign", class extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" }).innerHTML = "<slot></slot>";
this.shadowRoot.adoptedStyleSheets = [sheet];
}
});- Line 4 gives the sign a crimson border when the tag has
dir="rtl". - Line 5 gives it a honeydew background, a very pale green, when it runs right to left.
<div dir="rtl"><tea-sign>شاي أخضر</tea-sign></div><script src="tea-sign.js"></script><script> const style = getComputedStyle(document.querySelector("tea-sign")); console.log('Crimson border from :host([dir="rtl"]):', style.borderColor === "rgb(220, 20, 60)" ? "yes" : "no"); console.log("Honeydew background from :host(:dir(rtl)):", style.backgroundColor === "rgb(240, 255, 240)" ? "yes" : "no");</script>The tag has no dir attribute, so :host([dir="rtl"]) can't match. :host(:dir(rtl)) asks which way the tag runs, and it runs right to left, like its parent.
- dir on a parent: the border prints
no, the backgroundyes. - dir on the tag: both print
yes. - dir="auto": the border prints
no, the backgroundyes.
div, but has no dir attribute of its own. So only :host(:dir(rtl)) matches it.The first choice is how real pages work. The page sets dir once, high up, and never on your tag. So :host([dir="rtl"]) would never match there. Older components used :host-context([dir="rtl"]) to look up the tree. That only works in Chrome, and it's deprecated. :host(:dir(rtl)) is the standard way, and the support box below shows where :dir() works.
A passenger on a train heading north doesn't wear a sign that says north. They go north because the train does. If you look for a sign on each passenger, you'll find almost none. If you ask where each one is going, every answer is right.
- In real life: The train's direction
- In JavaScript: The
diron the page or a parent - In real life: A sign pinned on one passenger
- In JavaScript: A
dirattribute on the tag itself - In real life: Asking which way the passenger is going
- In JavaScript:
:dir(rtl) - In real life: Looking for a sign on the passenger
- In JavaScript:
[dir="rtl"]
The third choice used dir="auto". The browser looks for the first letter that has a direction. The HTML Standard calls it a very crude guess. Here the first letter is Arabic, so the sign runs right to left. It's like a waiter who answers in the language of your first word. Use auto for text you can't know ahead, like a customer's review. On a host, it reads the page's text inside the tag. It doesn't read the words in the shadow root.
In JavaScript, ask the same question with this.matches(":dir(rtl)"). Lesson 14.2 compared it with getComputedStyle(this).direction, which the kit's arrow keys read. Lesson 14.3 gave the kit's tabs that key swap.
Why it matters: a component never knows where the page put dir. :dir() finds the direction wherever it came from.
Does dir inherit into shadow DOM?
Yes. MDN's shadow DOM guide says dir and lang come from an element's parent. When the parent is a shadow root, they come from the host. So everything inside a component runs the way its host runs. Even a reset can't stop that: lesson 11.1 showed that all: initial leaves direction alone.
Slotted content is the odd one out. Ravi builds tea-code to show an order code, like LK-204. A code like that reads left to right, even on an Arabic page. So the component wraps its slot in a left-to-right span:
customElements.define("tea-code", class extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" }).innerHTML = `
<span id="label">رمز الطلب:</span>
<span dir="ltr" lang="en"><slot></slot></span>`;
}
});- Line 5 is a label in the shadow root. It says order code in Arabic.
- Line 6 wraps the slot in a span with
dir="ltr"andlang="en".
<div dir="rtl" lang="ar"> <tea-code><b>LK-204</b></tea-code></div><script src="tea-code.js"></script><script> const host = document.querySelector("tea-code"); const show = (name, element) => { const style = getComputedStyle(element); console.log(`${name}: matches :dir(rtl) ${element.matches(":dir(rtl)")}, lays out ${style.direction}`); }; show("label", host.shadowRoot.getElementById("label")); show("slot", host.shadowRoot.querySelector("slot")); show("code", document.querySelector("b"));</script>- Line 2 puts the code, a bold LK-204, in the slot.
- Line 9 prints two answers for an element. Does it match
:dir(rtl)? And which way does CSS lay it out? That second answer is the computeddirection. - Lines 11 to 13 ask about the label, the slot, and the code.
label: matches :dir(rtl) true, lays out rtl. It took its direction from the host.slot: matches :dir(rtl) false, lays out ltr. Its parent is the left-to-right span.code: matches :dir(rtl) true, lays out ltr. The two answers disagree.
Here's why. Slotting doesn't change an element's parent. As lesson 8.2 showed, the bold code still lives in the page, inside tea-code. :dir() asks that parent, so it says right to left. But the browser draws the code in the slot, in the flat tree. CSS properties like direction are inherited through the flat tree. So it lays out left to right, like the slot.
tea-code, inside the right-to-left div, so it matches :dir(rtl). On the right, the browser draws it in the slot, inside the left-to-right span, so it lays out left to right.An exchange student from Oman lives with a family in London for a year. Her passport still says Oman. But at dinner, she follows the house rules of the family she lives with. Ask where she's from, and you get one answer. Watch how she lives, and you see another.
- In real life: The student's passport
- In JavaScript:
:dir(), from the parent in the page - In real life: The host family's house rules
- In JavaScript: CSS
direction, from the slot - In real life: The host family's home
- In JavaScript: The component's shadow root
lang works the same way: the code matches :lang(ar), and the slot matches :lang(en). And logical properties follow the layout. A margin-inline-start on the code is its left margin here, because it lays out left to right. Exercise 5 lets you check that.
Why it matters: inside a component, style slotted content with logical properties. They follow the slot it's shown in. And only put a dir around a slot when you mean it, like for this code.
Which icons should flip in right-to-left layouts?
Mariam's menu has a Next tea button with an arrow. In English, it points right, toward the end of the line. In Arabic, the end of the line is on the left. So the arrow has to point left. But the teacup in the shop's logo shouldn't turn around. Which icons flip?
No web standard lists them. Decide by what each icon means. Flip it when it points along the line of text: back, forward, next, or arrows between steps. Keep it when it shows a real thing or a sign:
- a logo, like the teacup;
- a clock, because clocks turn clockwise everywhere;
- a check mark, which means done and points nowhere;
- media buttons like play, which show the way a tape runs, not the way you read.
Design systems write their own lists from the same idea. Material Design mirrors back and forward icons, keeps clocks as they are, and keeps media controls left to right. Its older guide sums it up: an arrow that means forward points left in a right-to-left layout.
Leaf and Kettle prints its menu in Arabic too. The booklet opens from the other side, and the little arrow that says "next page" points left. The logo on the cover is the same as on the English menu. So is the clock that shows the opening hours.
- In real life: The "next page" arrow in the corner
- In JavaScript: The next and back icons, which flip
- In real life: The shop's logo on the cover
- In JavaScript: The cup icon, which stays
- In real life: The clock that shows opening hours
- In JavaScript: The clock icon, which stays
The kit's new version adds tea-icon. It draws six small icons in the text color, and knows which ones flip. These are its main lines, from the tea-icon.js tab:
const icons = new Map([
["next", { flips: true, shape: '<path d="M2 8h11M9 4l4 4-4 4"/>' }],
["back", { flips: true, shape: '<path d="M14 8H3M7 4 3 8l4 4"/>' }],
["cup", { flips: false, shape: '<path d="M2 6h9v2a4 4 0 0 1-4 4H6a4 4 0 0 1-4-4zM11 7h1a2 2 0 0 1 0 4h-1"/>' }],
["check", { flips: false, shape: '<path d="M3 8l3 3 7-7"/>' }],
["clock", { flips: false, shape: '<circle cx="8" cy="8" r="6"/><path d="M8 5v3l2 2"/>' }],
["play", { flips: false, shape: '<path d="M5 3v10l8-5z"/>' }],
]);
:host(:dir(rtl)) .flips { transform: scaleX(-1); }
attributeChangedCallback(name, oldValue, newValue) {
const icon = icons.get(newValue);
const svg = this.shadowRoot.querySelector("svg");
svg.innerHTML = icon?.shape ?? "";
svg.classList.toggle("flips", icon?.flips ?? false);
}- Lines 1 to 8 list the icons. Next and back have
flips: true. The cup, check, clock, and play havefalse. - Line 10 is the whole flip: on a right-to-left page,
transform: scaleX(-1)mirrors the drawing left to right. - Lines 15 and 16 draw the chosen icon, and give it the
flipsclass when it should flip.
<div dir="ltr" lang="en"> <button>Next tea <tea-icon name="next"></tea-icon></button> <button><tea-icon name="back"></tea-icon> Back to the menu</button> <p><tea-icon name="cup"></tea-icon> <tea-icon name="check"></tea-icon> <tea-icon name="clock"></tea-icon> <tea-icon name="play"></tea-icon></p></div><script type="module"> import "./tea-kit/index.js"; for (const icon of document.querySelectorAll("tea-icon")) { const svg = icon.shadowRoot.querySelector("svg"); console.log(`${icon.getAttribute("name")}: ${getComputedStyle(svg).transform === "none" ? "as drawn" : "flipped"}`); }</script>The next arrow points right, toward the end of the line. Nothing is flipped.
- English prints
as drawnfor all six icons. - Arabic prints
next: flippedandback: flipped. The other four stayas drawn.
Line 10 of the page reads the svg's computed transform. A flipped icon has matrix(-1, 0, 0, 1, 0, 0): the x axis turned around. The rule uses :host(:dir(rtl)), so the icon follows the direction of the words it sits next to.
Motion follows the same idea. The card's steam keyframes move only on the y axis:
from { opacity: 0; translate: 0 0; }
to { opacity: 0; translate: 0 calc(var(--tea-motion, 1) * -16px); }Steam rises in every language, so nothing flips. A card that slid in toward the end of the line would need to flip.
- The arrow on a Next tea button.
- The arrow on a Back to the menu button.
- Arrows between the steps Choose, Brew, and Pour.
- The teacup in Leaf and Kettle's logo.
- A clock showing how long the tea brews.
- A check mark next to a tea you added.
- The play button on a brewing video.
- Steam rising from the card.
Sort each picture by what it should do on a right-to-left page.
Why it matters: a wrong arrow sends a reader the wrong way. A flipped logo or clock just looks broken.
Converting the tea kit to logical properties
Back to the two bugs from the start. Ravi searches the kit's sheets for physical names: left, right, top, bottom, width, height, and margins, paddings, or borders with a side. He also looks for anything that moves sideways, like translate.
Two of them were real bugs. Here they are, before and after, shortened:
/* tea-card.js, the steam: before */
.steam { position: absolute; top: 6px; right: 12px; width: 6px; height: 14px; … }
/* after */
.steam { position: absolute; inset-block-start: 6px; inset-inline-end: 12px; inline-size: 6px; block-size: 14px; … }
/* tea-toggle.js, the thumb when on: before */
:host(:state(checked)) .thumb { translate: 16px 0; }
/* after */
:host(:state(checked)) .thumb { margin-inline-start: 16px; }- Line 2 pinned the steam to the right corner. Line 4 puts it at the end corner instead: the top right in English, the top left in Arabic.
- Line 7 moved the thumb 16px right. On a right-to-left page, the thumb starts on the right, so it left the track. Line 9 moves it toward the end of the track instead, with a logical margin.
Here is the overview's page again, measuring both. Pick a version of the kit:
<link rel="stylesheet" href="tea-kit/tokens.css"><div dir="rtl" lang="ar"> <tea-card><span slot="name">شاي أخضر</span></tea-card> <tea-toggle checked>مع حليب</tea-toggle></div><script type="module"> import "./tea-kit/index.js"; const box = (root, selector) => root.querySelector(selector).getBoundingClientRect(); const card = document.querySelector("tea-card"); const steam = box(card.shadowRoot, ".steam"); const name = box(card, "span"); console.log("Steam over the name:", steam.left < name.right && steam.right > name.left); const toggle = document.querySelector("tea-toggle").shadowRoot; const track = box(toggle, ".track"); const thumb = box(toggle, ".thumb"); console.log("Thumb inside its track:", thumb.left >= track.left && thumb.right <= track.right);</script>right: 12px keeps the steam at the card's right corner, where an Arabic name starts. translate: 16px 0 moves the thumb right, but it already starts on the right.
- Lines 1 to 5 are the overview's page.
- Line 12 checks whether the steam's box and the name's box overlap from side to side.
- Line 16 checks whether the thumb stays between the ends of its track.
- kitAfter151:
Steam over the name: trueandThumb inside its track: false. - kitAfter152:
Steam over the name: falseandThumb inside its track: true.
The other physical names weren't bugs, but the kit changes them too, so its sheets use one system. Read each row across:
| Where | What it said | What it says now | What changes on a right-to-left page |
|---|---|---|---|
| tea-card's steam. | top: 6px; right: 12px | inset-block-start: 6px; inset-inline-end: 12px | The steam moves to the top left corner, away from the name. |
| tea-toggle's thumb, when on. | translate: 16px 0 | margin-inline-start: 16px | The thumb slides left, and stays inside its track. |
| Sizes in tea-card, tea-toggle, tea-search, and tea-details. | width, height, and min-width | inline-size, block-size, and min-inline-size | Nothing. Arabic lines run sideways too, so inline-size is still the width. |
| tea-card's buy row. | margin-top | margin-block-start | Nothing. The top is the block start in both directions. |
| tea-card's container query. | min-width: 320px | min-inline-size: 320px | Nothing. It still measures the card's width. |
| tea-tabs' line under the row. | border-bottom | border-block-end | Nothing. The vertical row already used border-inline-end. |
The container query now asks for min-inline-size: 320px. Lesson 12.5 wrote it with min-width, and both measure the card's width here.
The kit's new version, kitAfter152, changes five files and adds one:
tea-card,tea-toggle,tea-tabs,tea-search, andtea-detailsuse logical names everywhere.tea-iconis new, with its six icons.- The JSDoc and
custom-elements.jsondescribe the steam's corner, the switch's direction, and the new icon.
Two checks prove the change. On left-to-right pages from earlier lessons, every box inside every component sits where it did, at the same size. On a right-to-left page, every box mirrors. The course's test measures both in Chrome.
Why it matters: the next lesson that uses the kit works in Arabic without a single extra rule.
Common mix-ups
- "Logical properties are only for vertical writing." No. In Arabic and Hebrew,
margin-inline-startis the right margin. That's the most common reason to use them. - "[dir="rtl"] finds every right-to-left element." No. It only finds elements that carry the attribute.
:dir(rtl)finds the rest. - ":host([dir="rtl"]) works when the page sets dir on <html>." No. Your tag has no
dirof its own. Use:host(:dir(rtl)). - "Setting direction: rtl in CSS is the same as dir="rtl"." No.
:dir()ignores the CSS property. Putdirin the markup. - "Slotted content lays out like the page around the component." No. It lays out like the slot it's shown in. Only
:dir()and:lang()follow the page. - "Every icon should be mirrored on a right-to-left page." No. Only icons that point along the line flip. Logos, clocks, check marks, and play stay as drawn.
- "inline-size means the height in Arabic." No. Arabic lines run sideways, so it's the width.
Practice exercises
Line 2 gives a paragraph margin-inline-end: 12px in a right-to-left box. Predict which side gets the 12px. Then run it.
<div dir="rtl"> <p style="margin-inline-end: 12px">شاي أخضر</p></div><script> const style = getComputedStyle(document.querySelector("p")); console.log("left:", style.marginLeft, "right:", style.marginRight);</script><div dir="rtl"> <p style="margin-inline-end: 12px">شاي أخضر</p></div><script> const style = getComputedStyle(document.querySelector("p")); console.log("left:", style.marginLeft, "right:", style.marginRight);</script>It prints left: 12px right: 0px. The box runs right to left, so each line ends on the left, and margin-inline-end becomes the left margin.
This sign has dir="auto" and English words, inside a right-to-left box. Does the honeydew background from :host(:dir(rtl)) show? Predict the second line.
<div dir="rtl"><tea-sign dir="auto">Sencha</tea-sign></div><script src="tea-sign.js"></script><script> const style = getComputedStyle(document.querySelector("tea-sign")); console.log('Crimson border from :host([dir="rtl"]):', style.borderColor === "rgb(220, 20, 60)" ? "yes" : "no"); console.log("Honeydew background from :host(:dir(rtl)):", style.backgroundColor === "rgb(240, 255, 240)" ? "yes" : "no");</script><div dir="rtl"><tea-sign dir="auto">Sencha</tea-sign></div><script src="tea-sign.js"></script><script> const style = getComputedStyle(document.querySelector("tea-sign")); console.log('Crimson border from :host([dir="rtl"]):', style.borderColor === "rgb(220, 20, 60)" ? "yes" : "no"); console.log("Honeydew background from :host(:dir(rtl)):", style.backgroundColor === "rgb(240, 255, 240)" ? "yes" : "no");</script>Both lines print no. auto ignores the div's rtl and reads the text. S is a left-to-right letter, so the sign runs left to right, and :host(:dir(rtl)) doesn't match.
The note should have its square corner where the words start. In Arabic, it prints square corner top left. Fix the component, not the page. Which corner is square then?
<div dir="rtl"><tea-note>طازج وعشبي.</tea-note></div><script src="tea-note.js"></script><script> for (const note of document.querySelectorAll("tea-note")) { const host = note.getBoundingClientRect(); const p = getComputedStyle(note.shadowRoot.querySelector("p")); const dot = note.shadowRoot.querySelector(".new").getBoundingClientRect(); const bar = p.borderLeftWidth === "4px" ? "left" : "right"; const corner = p.borderTopLeftRadius === "0px" ? "left" : "right"; const near = host.right - dot.right === 6 ? "right" : "left"; console.log(`${note.parentElement.dir}: ${host.width}px wide, bar on the ${bar}, square corner top ${corner}, dot top ${near}`); }</script><div dir="rtl"><tea-note>طازج وعشبي.</tea-note></div><script src="tea-note.js"></script><script> for (const note of document.querySelectorAll("tea-note")) { const host = note.getBoundingClientRect(); const p = getComputedStyle(note.shadowRoot.querySelector("p")); const dot = note.shadowRoot.querySelector(".new").getBoundingClientRect(); const bar = p.borderLeftWidth === "4px" ? "left" : "right"; const corner = p.borderTopLeftRadius === "0px" ? "left" : "right"; const near = host.right - dot.right === 6 ? "right" : "left"; console.log(`${note.parentElement.dir}: ${host.width}px wide, bar on the ${bar}, square corner top ${corner}, dot top ${near}`); }</script>The tea-note.js tab changes: line 5 uses border-start-start-radius: 0. In a right-to-left box, the start of the line is on the right, so the page prints square corner top right.
The Back to the menu arrow should point right on an Arabic page. It prints Arrow: none. Fix the component's rule. What does the page print then?
<div dir="rtl" lang="ar"> <tea-back>العودة إلى القائمة</tea-back></div><script src="tea-back.js"></script><script> const svg = document.querySelector("tea-back").shadowRoot.querySelector("svg"); console.log("Arrow:", getComputedStyle(svg).transform);</script><div dir="rtl" lang="ar"> <tea-back>العودة إلى القائمة</tea-back></div><script src="tea-back.js"></script><script> const svg = document.querySelector("tea-back").shadowRoot.querySelector("svg"); console.log("Arrow:", getComputedStyle(svg).transform);</script>Line 4 of the tea-back.js tab becomes :host(:dir(rtl)) svg. The attribute selector never matched, because the tag has no dir. :dir(rtl) sees the direction it inherited, so the arrow flips: Arrow: matrix(-1, 0, 0, 1, 0, 0).
The page gives the order code two rules: a crimson color for :dir(rtl), and margin-inline-start: 8px. Is the code crimson? Which side gets its 8px margin?
<style> b { margin-inline-start: 8px; } b:dir(rtl) { color: crimson; }</style><div dir="rtl" lang="ar"> <tea-code><b>LK-204</b></tea-code></div><script src="tea-code.js"></script><script> const style = getComputedStyle(document.querySelector("b")); console.log("Color:", style.color); console.log("Left margin:", style.marginLeft, "Right margin:", style.marginRight);</script><style> b { margin-inline-start: 8px; } b:dir(rtl) { color: crimson; }</style><div dir="rtl" lang="ar"> <tea-code><b>LK-204</b></tea-code></div><script src="tea-code.js"></script><script> const style = getComputedStyle(document.querySelector("b")); console.log("Color:", style.color); console.log("Left margin:", style.marginLeft, "Right margin:", style.marginRight);</script>It prints Color: rgb(220, 20, 60): the page's b:dir(rtl) rule matches, because the code's parent runs right to left. Then Left margin: 8px Right margin: 0px: the code lays out left to right, like the slot, so its inline start is on the left.
tea-switch is on, in a right-to-left box, and it prints Thumb inside its track: false. Fix the component. What does the page print then?
<div dir="rtl"><tea-switch on></tea-switch></div><script src="tea-switch.js"></script><script> const root = document.querySelector("tea-switch").shadowRoot; const track = root.querySelector(".track").getBoundingClientRect(); const thumb = root.querySelector(".thumb").getBoundingClientRect(); console.log("Thumb inside its track:", thumb.left >= track.left && thumb.right <= track.right);</script><div dir="rtl"><tea-switch on></tea-switch></div><script src="tea-switch.js"></script><script> const root = document.querySelector("tea-switch").shadowRoot; const track = root.querySelector(".track").getBoundingClientRect(); const thumb = root.querySelector(".thumb").getBoundingClientRect(); console.log("Thumb inside its track:", thumb.left >= track.left && thumb.right <= track.right);</script>The tea-switch.js tab changes: line 5 becomes :host([on]) .thumb { margin-inline-start: 16px; }. A logical margin moves the thumb toward the end of the track, which is left here. The page prints Thumb inside its track: true. A :dir(rtl) rule with translate: -16px 0 also works.
Check your understanding
Question 1 of 7What does the logical line print in this right-to-left box?
Read the code, then predict<style> p { border: 2px solid seagreen; } .physical { margin-left: 24px; } .logical { margin-inline-start: 24px; } </style> <div dir="rtl"> <p class="physical">margin-left</p> <p class="logical">margin-inline-start</p> </div> <script> for (const p of document.querySelectorAll("p")) { const style = getComputedStyle(p); console.log(`${p.className}: left ${style.marginLeft}, right ${style.marginRight}`); } </script>Choose an answer to see the explanation.
Question 2 of 7On an Arabic page, which physical property does
inline-sizeset?Choose an answer to see the explanation.
Question 3 of 7The page sets dir="rtl" on a div around a component. Which rule in the component's sheet matches the host?
Choose an answer to see the explanation.
Question 4 of 7A tag has dir="auto" and holds the Arabic words شاي أخضر. Which way does it run?
Choose an answer to see the explanation.
Question 5 of 7A component wraps its slot in <span dir="ltr">. On a right-to-left page, the slotted <b> has no dir. What is true of it?
Choose an answer to see the explanation.
Question 6 of 7Which icon should flip on a right-to-left page?
Choose an answer to see the explanation.
Question 7 of 7Why does kitAfter152 move the switch's thumb with
margin-inline-start: 16pxinstead oftranslate: 16px 0?Choose an answer to see the explanation.
Key takeaways
- Logical properties name the start and end of a line, not left and right. In Arabic,
margin-inline-startis the right margin. - The browser turns each logical property into a physical one, using the element's direction.
inline-sizeis still the width in Arabic. Only vertical writing turns it into the height.- Set direction with the
dirattribute:ltr,rtl, orauto. - In a component, use
:host(:dir(rtl)).:host([dir="rtl"])only sees adiron the tag itself. - Shadow roots take
dirandlangfrom the host. Slotted content matches:dir()by its parent in the page, but lays out like its slot. - Flip an icon only when it points along the line. Logos, clocks, check marks, and play stay as drawn.
Remember the one-liner.
Say start and end, not left and right, and flip only what points along the line.
Sources
The facts on this page come from these standards, docs, and guides:
- Basic concepts of logical properties and values, MDN.
- Logical properties for margins, borders, and padding, MDN.
- Logical properties for sizing, MDN.
- margin-inline-start, MDN.
- dir, MDN.
- HTML Standard: the dir attribute, WHATWG.
- :dir(), MDN.
- Using shadow DOM: attribute inheritance, MDN.
- Bidirectionality and RTL, Material Design 3.
- Bidirectionality, Material Design 2.
- browser-compat-data, MDN.
Coming next: Testing accessibility, in Accessible components. It tests components with screen readers, the accessibility tree, and automated tools that see shadow DOM.