completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

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.

By the end, you can
  • 01
    Write CSS that works in both directionsUse logical properties like margin-inline-start and inset-inline-end, so start and end follow the page's direction.
  • 02
    Know which way a component runsStyle it with :host(:dir(rtl)), and tell where dir reaches inside a shadow root and where slotted content takes it from.
  • 03
    Flip 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:

The tea card and the switch on an Arabic pagePop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • Line 1 links the kit's tokens, the values every component shares.
  • Line 2 sets the direction with dir="rtl" and the language with lang="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.

Real-life analogyTwo shops with mirror-image rooms

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"
The main idea

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:

Playground: margin-left or margin-inline-start?
A physical margin and a logical marginPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
Try it yourself
Left to right: both margins are on the left

In English, the start of a line is its left end. So margin-inline-start is the left margin, the same as margin-left.

Only line 6, the box's dir, changes. Each line it prints is one paragraph's left and right margins.
  • 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 print left 24px, right 0px.
  • With dir="rtl", the physical one still prints left 24px, right 0px. The logical one prints logical: left 0px, right 24px.
Two browser windows. In the left one, dir="ltr", an arrow runs from start on the left to end on the right. A card labelled margin-inline-start has a 24px gap on its left, and a card labelled margin-left has a 24px gap on its left. In the right one, dir="rtl", the arrow runs from start on the right to end on the left. The margin-inline-start card now has its 24px gap on the right, and the margin-left card still has its gap on the left.dir="ltr"startendmargin-inline-start24pxmargin-left24pxdir="rtl"startendmargin-inline-start24pxmargin-left24px
The arrow runs from where a line starts to where it ends. 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:

Physical names and their logical names
If you wroteWrite insteadWhat it means on a right-to-left page
margin-leftmargin-inline-startThe right margin, where each line starts.
padding-rightpadding-inline-endThe left padding, where each line ends.
padding-left and padding-rightpadding-inline: 12px 24px12px on the right and 24px on the left: start first, then end.
border-leftborder-inline-startThe border on the right.
right: 8pxinset-inline-end: 8px8px from the left edge.
border-top-left-radiusborder-start-start-radiusThe top right corner.
text-align: lefttext-align: startThe words line up on the right.
width and heightinline-size and block-sizeStill the width and the height. Arabic lines run sideways too.
margin-topmargin-block-startStill 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:

tea-note.js: a tasting note written with logical propertiesJavaScript
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 with margin-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 with border-inline-start. text-align: start lines 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-start and inset-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:

The same note, left to right and right to leftPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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 right
  • rtl: 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 translate on 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:

tea-sign.js: one rule for the attribute, one for the directionJavaScript
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.
Playground: which rule matches?
A sign on a right-to-left pagePop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
Try it yourself
Only :dir(rtl) sees a direction it inherited

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.

Only line 1 changes. The page prints which of the sign's two rules matched.
  • dir on a parent: the border prints no, the background yes.
  • dir on the tag: both print yes.
  • dir="auto": the border prints no, the background yes.
On the left, a crate labelled div dir="rtl" holds a card labelled tea-sign, with a note that the tag has no dir attribute. On the right, two rules. Under :host([dir="rtl"]), a note says it does not match, because there is no dir on the tag. Under :host(:dir(rtl)), a note says it matches, because the tag runs right to left.<tea-sign>no dir attribute<div dir="rtl">:host([dir="rtl"])no match: no dir on the tag:host(:dir(rtl))matches: it runs right to left
The tag runs right to left, like its 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.

Real-life analogyPassengers go the way the train goes

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 dir on the page or a parent
In real life: A sign pinned on one passenger
In JavaScript: A dir attribute 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:

tea-code.js: an order code that always reads left to rightJavaScript
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" and lang="en".
Three parts of tea-code, asked two questionsPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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 computed direction.
  • 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.

Two trees for the order code. On the left, the node tree: div dir="rtl", then tea-code, then the b element with LK-204. A note says :dir(rtl) is true, because it asks its parent. On the right, the flat tree: span dir="ltr", then slot, then the same b element. A note says direction is ltr, because it lays out like the slot.node tree<div dir="rtl"><tea-code><b>LK-204</b>:dir(rtl) is trueit asks its parentflat tree<span dir="ltr"><slot><b>LK-204</b>direction: ltrit lays out like the slot
On the left, the code's parent is 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.
Real-life analogyAn exchange student

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.

Real-life analogyA printed Arabic menu

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:

tea-icon.js: icons that flip, and one rule to flip themJavaScript
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 have false.
  • 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 flips class when it should flip.
Playground: the kit's icons in English and in Arabic
Buttons and icons from tea-iconPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
Try it yourself
Every icon as it's drawn

The next arrow points right, toward the end of the line. Nothing is flipped.

Lines 1 to 3 change with the language. The page prints whether each icon is flipped.
  • English prints as drawn for all six icons.
  • Arabic prints next: flipped and back: flipped. The other four stay as drawn.
Two rows of icons. The left to right row shows next with an arrow pointing right, back with an arrow pointing left, cup, and clock. The right to left row shows next with an arrow pointing left, back with an arrow pointing right, cup, and clock. Notes under the columns say the two arrows flip and the cup and clock stay.left to rightnext →back ←cupclockright to leftnext ←back →cupclockflipsflipsstaysstays
Next and back point along the line, so they turn around in Arabic. The cup and the clock keep their shape.

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:

tea-card's steam keyframes, in both versions of the kitCSS
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.

Flip it or keep it?
  • 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.
Try it yourself
0 of 8 correct

Sort each picture by what it should do on a right-to-left page.

Choose a category for every card. You can change an answer at any time; Reset clears them all.

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:

The two rules that broke right to left, before and afterCSS
/* 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:

Playground: the Arabic menu, before and after
The Arabic menu, measuring the steam and the thumbPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
Try it yourself
The steam covers the name, and the thumb leaves its track

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.

The page stays the same. Only the kit in the tabs changes.
  • 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: true and Thumb inside its track: false.
  • kitAfter152: Steam over the name: false and Thumb 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:

Every physical name in the kit's sheets
WhereWhat it saidWhat it says nowWhat changes on a right-to-left page
tea-card's steam.top: 6px; right: 12pxinset-block-start: 6px; inset-inline-end: 12pxThe steam moves to the top left corner, away from the name.
tea-toggle's thumb, when on.translate: 16px 0margin-inline-start: 16pxThe thumb slides left, and stays inside its track.
Sizes in tea-card, tea-toggle, tea-search, and tea-details.width, height, and min-widthinline-size, block-size, and min-inline-sizeNothing. Arabic lines run sideways too, so inline-size is still the width.
tea-card's buy row.margin-topmargin-block-startNothing. The top is the block start in both directions.
tea-card's container query.min-width: 320pxmin-inline-size: 320pxNothing. It still measures the card's width.
tea-tabs' line under the row.border-bottomborder-block-endNothing. 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, and tea-details use logical names everywhere.
  • tea-icon is new, with its six icons.
  • The JSDoc and custom-elements.json describe 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-start is 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 dir of its own. Use :host(:dir(rtl)).
  • "Setting direction: rtl in CSS is the same as dir="rtl"." No. :dir() ignores the CSS property. Put dir in 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

Exercise 1 · Warm-upThe end of an Arabic line

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>
ResultLoading…

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · Warm-upauto with English words

    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>
    ResultLoading…

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeThe square corner

      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>
      ResultLoading…

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeThe back arrow that won't flip

        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>
        ResultLoading…

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeTwo answers for one code

          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>
          ResultLoading…

          Answer, then press Check. Spacing and letter case don’t matter.

            Exercise 6 · ChallengeA switch that leaves its track

            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>
            ResultLoading…

            Answer, then press Check. Spacing and letter case don’t matter.

              Check your understanding

              The right-to-left quiz · 7 questionsScore: first tries count
              1. Question 1 of 7What does the logical line print in this right-to-left box?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                <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.

              2. Question 2 of 7On an Arabic page, which physical property does inline-size set?

                Choose an answer to see the explanation.

              3. 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.

              4. 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.

              5. 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.

              6. Question 6 of 7Which icon should flip on a right-to-left page?

                Choose an answer to see the explanation.

              7. Question 7 of 7Why does kitAfter152 move the switch's thumb with margin-inline-start: 16px instead of translate: 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-start is the right margin.
              • The browser turns each logical property into a physical one, using the element's direction.
              • inline-size is still the width in Arabic. Only vertical writing turns it into the height.
              • Set direction with the dir attribute: ltr, rtl, or auto.
              • In a component, use :host(:dir(rtl)). :host([dir="rtl"]) only sees a dir on the tag itself.
              • Shadow roots take dir and lang from 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:

              Coming next: Testing accessibility, in Accessible components. It tests components with screen readers, the accessibility tree, and automated tools that see shadow DOM.

              CompleteFrontend Clear concepts. Working examples.