Skip to content
AITroveRead. Build. Understand.
Make this comfortable

CSS :dir(): respond to computed text direction

Last updated: 5 Oct 20265 min read
tutorial
BeginnerBy AITrove Editorial

The :dir() pseudo-class matches an element by its text direction, including direction inherited from an ancestor or resolved from dir=auto. An attribute selector such as [dir=rtl] only finds an explicit attribute. CSS direction changes layout behavior but does not make :dir() match a new semantic direction; put the correct direction in HTML.

When to use it

A case review page displays an Arabic customer note inside an otherwise left-to-right interface. The note's HTML establishes its direction; a nested action row inherits that direction even though it has no dir attribute. A :dir(rtl) rule adjusts the row's border and alignment, while logical padding and margin work for either direction. Test an Arabic note, an English note, a mixed numeric identifier, and a note whose dir=auto resolves differently after its text changes. Do not reverse characters with transforms or reorder controls merely for visual symmetry. Keep numbers, links, and punctuation readable in mixed-script content, and verify with actual localized strings rather than a Latin placeholder. A language tag and a direction attribute answer different questions. The former helps pronunciation and typographic conventions; the latter establishes bidirectional layout. The selector is useful only after the document has the right semantics.

css
.case-note { padding-inline: 1rem; border-inline-start: .25rem solid #396c82; }
.case-note:dir(rtl) .case-note__actions { text-align: start; border-inline-start: .15rem solid #819aa5; }
.case-note:dir(ltr) .case-note__actions { text-align: start; border-inline-start: .15rem solid #396c82; }

Cost and verification

Selector matching is cheap; the cost is translation and bidirectional testing. A stylesheet cannot infer the intended reading direction from a username or code token. Keep the HTML dir value correct, especially when a component receives user-provided text. A [dir=rtl] shortcut misses inherited and auto-resolved cases, while a global direction override can disturb unrelated form controls. The CSS sample deliberately uses logical borders so its geometry follows writing direction without duplicate left/right coordinates. Verify keyboard order and screen reader output separately from painted alignment. Direction-aware decoration must never be the only indication of who authored a note or what language it contains.

Common Mistakes

  • Do not treat [dir=rtl] as equivalent to :dir(rtl).
  • Do not expect CSS direction to establish the semantic direction matched by :dir().
  • Do not use transforms to fake right-to-left reading order.

Connected lessons

css
reference
web
Storage details