What is Direction in CSS: Explanation and Examples
direction property in CSS sets the text and layout flow direction of content, either left-to-right (ltr) or right-to-left (rtl). It is mainly used to support languages that read in different directions, like English (ltr) or Arabic (rtl).How It Works
The direction property controls the horizontal flow of text and elements inside a container. Think of it like deciding which way you read a book: in English, you read from left to right, but in Arabic or Hebrew, you read from right to left. CSS uses direction to tell the browser how to arrange text and some layout features accordingly.
When you set direction: ltr;, the content starts from the left side and flows to the right. When you set direction: rtl;, the content starts from the right side and flows to the left. This affects text alignment, the position of punctuation, and the order of elements in some cases.
It’s like setting the reading direction for a paragraph or a whole page, so the browser knows how to display the content naturally for different languages.
Example
This example shows two paragraphs: one with left-to-right direction and one with right-to-left direction. Notice how the text alignment and flow change.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CSS Direction Example</title> <style> .ltr { direction: ltr; border: 1px solid #333; padding: 10px; margin-bottom: 10px; } .rtl { direction: rtl; border: 1px solid #333; padding: 10px; } </style> </head> <body> <p class="ltr">This text flows from left to right (English style).</p> <p class="rtl">هذا النص يتدفق من اليمين إلى اليسار (نمط اللغة العربية).</p> </body> </html>
When to Use
Use the direction property when you need to support languages that read right-to-left, such as Arabic, Hebrew, or Persian. It ensures your website content looks natural and readable for users of those languages.
It also helps when you want to create layouts or components that flip horizontally, like chat bubbles or navigation menus, to match the reading direction.
For example, if you build a multilingual website, you can switch the direction property dynamically based on the user's language choice to improve usability and accessibility.
Key Points
- direction controls text and layout flow horizontally.
- Common values are
ltr(left-to-right) andrtl(right-to-left). - It is essential for supporting languages with different reading directions.
- Affects text alignment, punctuation placement, and some layout behaviors.
- Works well with other CSS properties like
unicode-bidifor complex text handling.
Key Takeaways
direction property sets text flow direction as left-to-right or right-to-left.direction to support languages like Arabic or Hebrew that read right-to-left.direction dynamically for multilingual websites to improve readability.unicode-bidi for advanced text direction control.