Skip to content

CSS :dir() Pseudo Class

The :dir() pseudo-class matches elements that are based on the directionality of the text contained in them.

The :dir() pseudo-class does not select based on stylistic states, which is why the directionality of an element needs to be specified in the document.

In HTML5, the directionality of an element can be specified using the dir attribute.

The :dir() selector can have either "ltr" or "rtl" values.

The pseudo-class :dir(ltr) matches elements that have a directionality of left-to-right. The pseudo-class :dir(rtl) matches elements that have a directionality of right-to-left. Other values are invalid.

:dir(rtl) vs. [dir=rtl]

There is a difference between :dir(rtl) and [dir=rtl]. [dir=rtl] only selects an element if the attribute is strictly defined in the HTML markup. :dir(rtl) selects the element even if the directionality is not explicitly stated in HTML. Elements without an explicit direction inherit the dir attribute from their closest ancestor that contains one. In these cases, [dir=rtl] does not match the inherited elements, while :dir(rtl) does.

Version

Selectors Level 4

Syntax

CSS :dir() syntax

css
:dir(ltr) {
  css declarations
}

Example of the :dir() selector:

CSS :dir() code example

html
<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      div:dir(ltr) {
        background-color: #1c87c9;
      }
      div:dir(rtl) {
        background-color: #8ebf42;
      }
    </style>
  </head>
  <body>
    <h2>:dir() selector example</h2>
    <div dir="rtl">
      <span>example1</span>
      <div dir="ltr">
        example2
        <div dir="auto"> ففي </div>
      </div>
    </div>
  </body>
</html>

note

This pseudo-class is supported in all modern browsers, including Chrome, Edge, Safari, and Firefox.

Practice

What is the purpose of the 'dir' property in CSS?

Dual-run preview — compare with live Symfony routes.