CSS :dir() Pseudo Class

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

The :dir() does not select based on stylistic states that 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) shows an element that has a directionality of left-to-right. The pseudo-class :dir(rtl) shows an element that has a directionality of right-to-left. Other values are not invalid but do not correspond to anything.

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

There is a difference between :dir(rtl) and [dir=rtl]. [dir=rtl] works but it only selects an element by what is strictly defined in the HTML markup. :dir(rtl) selects the element without being explicitly stated in HTML. Elements not explicitly stating the language direction inherit the dir attribute of its closest ancestor that contains one. In these cases, [dir=rtl] selects additional elements.

Version

Selectors Level 4

Syntax

:dir() {
  css declarations
}

Example of the :dir() selector:

<!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>

To see the effect use Firefox because this pseudo-class works only on Mozilla Firefox.

Browser support

chrome edge firefox safari opera
49.0+
17.0 - 48.0 -moz-

Practice Your Knowledge

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

Quiz Time: Test Your Skills!

Ready to challenge what you've learned? Dive into our interactive quizzes for a deeper understanding and a fun way to reinforce your knowledge.

Do you find this helpful?