HTML

Text Direction


In HTML, you can control text direction using the dir attribute. This attribute can be applied to any HTML element to specify its text direction.

 

dir Attribute Values

  • ltr: Left to right. Used for languages such as English.
  • rtl: Right to left. Used for languages such as Arabic and Hebrew.
  • auto: The browser determines the text direction based on the content.
  •  

Examples

Example 1: Basic Usage

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Text Direction Example</title>
</head>
<body>
    <!-- Left to Right Text (default) -->
    <p>This text is left to right.</p>

    <!-- Right to Left Text -->
    <p dir="rtl">هذا النص من اليمين إلى اليسار.</p>

    <!-- Automatic Text Direction -->
    <p dir="auto">هذا النص سوف يتحدد اتجاهه تلقائيًا.</p>
</body>
</html>

In this example:

  • The first paragraph is displayed in the default left-to-right direction.
  • The second paragraph is explicitly set to display in a right-to-left direction using dir="rtl".
  • The third paragraph uses dir="auto" which lets the browser decide the direction based on the content.

 

Example 2: Mixed Content

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mixed Text Direction Example</title>
</head>
<body>
    <!-- Mixed content with explicit direction -->
    <p dir="rtl">This is a right-to-left text: هذا نص من اليمين إلى اليسار.</p>
    <p dir="ltr">This is a left-to-right text: זהו טקסט משמאל לימין.</p>
</body>
</html>

In this example:

  • The first paragraph is set to right-to-left, but it contains a mix of English and Arabic.
  • The second paragraph is set to left-to-right, but it contains a mix of English and Hebrew.