:dir()

The :dir() pseudo-class in CSS allows elements to be selected based on the direction of the language, as determined in the HTML markup. There are really only two directions language can flow in a document, which are left-to-right and right-to-left. Think of this as a way to style elements that are distinguished by different language directionality.

<div class="item">
	<!-- Content -->
</div>
<div class="item" dir="rtl">
	<!-- Content -->
</div>
.item:dir(rtl) {
  background: red;
  color: #fff;
}

The pseudo-class only accepts a single value and will return null if more than one value is entered.

See the Pen :dir pseudo-selector by Geoff Graham (@geoffgraham) on CodePen.

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

We can also select an element based on its language direction by making using a match query selector:

.item[dir=rtl] {
  background: red;
  color: #fff;
}

That does indeed work, but is different from :dir(rtl) in that it only selects an element by what is strictly defined in the HTML markup. On the flip-side, :dir(rtl) will sniff out the user agent's language preferences and select the element without being explicitly stated in the HTML.

This is a big deal because elements that do not explicitly state the language direction will inherit the dir attribute of its closest ancestor that contains one. That can lead to a scenario where using [dir=rtl] selects additional elements than you intend.

Browser Support

This browser support data is from Caniuse, which has more detail. A number indicates that browser supports the feature at that version and up.

Desktop

ChromeOperaFirefoxIEEdgeSafari
NoNo17*NoNoNo

Mobile / Tablet

iOS SafariOpera MobileOpera MiniAndroidAndroid ChromeAndroid Firefox
NoNoNoNoNo56

More Information

This comment thread is closed. If you have important information to share, please contact us.
icon-anchoricon-closeicon-emailicon-linkicon-logo-staricon-menuicon-nav-guideicon-searchicon-staricon-tag