Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / CSS

:dir() — directionality pseudo-class

The :dir() pseudo-class selects elements by directionality established through HTML rules, not the CSS direction property. It distinguishes ltr from rtl and accounts for inheritance and dir="auto".

Version: CSS modules; structured CSSWG indexes reconciled with pinned MDN BCD; Chromium 152 scope gate, per-example verification still required

Syntax

:dir(ltr)
:dir(rtl)

:dir() matches an element by its semantic directionality. :dir(ltr) means left-to-right directionality, while :dir(rtl) means right-to-left. In HTML, directionality follows document rules, including the dir attribute, inheritance, and automatic direction detection.

The selector [dir="rtl"] only checks the attribute on the element itself. In contrast, :dir(rtl) can also match a descendant without that attribute. With dir="auto", the element matches either :dir(ltr) or :dir(rtl) according to its resolved directionality; :dir(auto) does not select such elements.

The argument must be a single identifier, not a string or list. Whitespace around it is allowed. In HTML, the argument is compared with the keywords ltr and rtl ASCII case-insensitively, so :dir(RTL) matches the same elements as :dir(rtl). Identifiers that do not match either keyword under this comparison are syntactically valid but match nothing. Empty :dir() is invalid.

The CSS direction property does not affect matching. The example separates inheritance, dir="auto", and styling: styled still matches :dir(ltr) despite direction: rtl.

Examples

<!doctype html>
<html lang="en" dir="ltr">
<meta charset="utf-8">
<title>:dir() example</title>
<style>
  .sample:dir(ltr) { border-left: 4px solid blue; }
  .sample:dir(rtl) { border-right: 4px solid green; }
</style>
<div dir="rtl">
  <p id="inherited" class="sample">Hello</p>
</div>
<p id="automatic" class="sample" dir="auto">שלום</p>
<p id="styled" class="sample" dir="ltr" style="direction: rtl">Hello</p>
<pre id="result"></pre>
<script>
  const lines = Array.from(document.querySelectorAll('.sample'), element =>
    `${element.id}: ${element.matches(':dir(rtl)') ? 'rtl' : 'ltr'}`
  );
  lines.push(`explicit rtl: ${document.querySelectorAll('.sample[dir="rtl"]').length}`);
  document.getElementById('result').textContent = lines.join('\n');
</script>
</html>

Result

inherited: rtl
automatic: rtl
styled: ltr
explicit rtl: 0

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources