Most stylesheets are written as if every reader reads left to right. Then a Persian or Arabic version is needed, and someone writes a second stylesheet full of [dir="rtl"] overrides that flip margins, paddings and floats. It works until the next feature ships and nobody remembers to add its override.

There is a simpler way. CSS has had logical properties for years, and every current browser supports them.

Physical vs logical

A physical property names a side of the screen: margin-left, padding-right, border-left. A logical property names a side of the text flow:

  • margin-inline-start is the side where a line starts. Left in English, right in Persian.
  • margin-inline-end is where a line ends.
  • margin-block-start and margin-block-end are the top and bottom in horizontal writing.

Set dir="rtl" on the html element and every logical property flips by itself. No second stylesheet.

.card { padding-inline: 1.5rem; border-inline-start: 3px solid var(--accent); text-align: start; } 

That card has its accent bar on the left in English and on the right in Arabic, with one rule.

The shorthands worth learning

  • padding-inline and margin-inline set both inline sides.
  • inset-inline-start replaces left for positioned elements.
  • border-start-start-radius is the top corner on the starting side.
  • text-align: start and text-align: end replace left and right.

Flexbox and grid already follow the writing direction. justify-content: flex-start puts items on the right in a right-to-left page, so most layouts need no change at all.

What still needs a look

A few things do not flip by themselves:

  1. Icons that point somewhere. An arrow meaning "next" should point left in Persian. I flip those with transform: scaleX(-1) under :dir(rtl), and only those. A search icon or a logo must not flip.
  2. Transforms and animations. translateX(20px) is physical. If a drawer slides in from the start side, the sign has to change with the direction.
  3. Numbers and code. Phone numbers, prices and code samples stay left to right inside right-to-left text. Wrapping them in <bdi> or giving them dir="ltr" keeps them readable.
  4. Fonts. Persian and Arabic need a font with proper shaping, and usually a slightly larger size and line height than Latin text at the same visual weight.

A migration path

You do not have to rewrite a whole stylesheet at once. I usually do it in this order:

  1. Add a lint rule (stylelint has liberty/use-logical-spec and similar plugins) that warns on new physical properties.
  2. Convert components as you touch them.
  3. Test with dir="rtl" on a page that has no translations yet. Broken alignment shows up immediately, even with English text.

When a site has to support English, German, Persian and Arabic, this is the difference between maintaining one layout and maintaining two.

Originally published on mkcodestudio.com.