CSS :dir() Pseudo Class

CSS :dir() Pseudo Class

CSS :dir() Pseudo-Class

The :dir() pseudo-class applies styles based on the text direction (ltr or rtl) of an element. It is useful for supporting multiple languages and ensuring proper layout adjustments.

1. Syntax

:dir(ltr) { text-align: left; } :dir(rtl) { text-align: right; }

Left-aligns text for LTR (left-to-right) languages like English.
Right-aligns text for RTL (right-to-left) languages like Arabic or Hebrew.

2. Example – Applying :dir() to a Paragraph

<p dir="ltr">This text is left-to-right.</p> <p dir="rtl">هذا النص من اليمين إلى اليسار.</p>
p:dir(ltr) { background-color: lightblue; text-align: left; } p:dir(rtl) { background-color: lightgreen; text-align: right; }

✅ The LTR paragraph gets a light blue background and aligns left.
✅ The RTL paragraph gets a light green background and aligns right.

3. Use Case – Styling Forms for Different Directions

<form dir="rtl"> <label>Name:</label> <input type="text" placeholder="أدخل اسمك"> </form>
input:dir(rtl) { text-align: right; direction: rtl; font-family: 'Tajawal', sans-serif; }

✅ Ensures Arabic/Hebrew forms display correctly.

4. :dir() vs [dir] Attribute Selector

Feature:dir()[dir]
Dynamic?Yes, applies even if the direction changes dynamicallyNo, applies only when the attribute is in HTML
SpecificityLowerHigher

:dir() is more flexible because it works even if direction changes via JavaScript.

5. Browser Support

BrowserSupport
✅ ChromeYes
✅ EdgeYes
✅ FirefoxYes
❌ SafariNo
❌ Internet ExplorerNo

6. Best Practices

✔ Use :dir() for responsive multilingual design.
✔ Combine with dir attributes for better control.
✔ Ensure RTL elements have proper font and layout support.

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close