htmlcssarabicbidi

Mixing RTL and LTR text in HTML


.red {
  color: red;
  direction: rtl;
}

.green {
  color: green;
  direction: rtl;
}

p {
  direction: ltr;
}
<p>Example: 
1. <span class="red">ااڡوںںطں، ااڡوںںطو</span> 
2. <span class="green">ااقونيطن هو قاتل النمر</span> 
</p>

The above HTML and CSS render like this:

sample of current output

Note that in the HTML 'red' comes before 'green' in the left-to-right order of things whereas the rendering has them swapped.

If I replace the '2.' with any Latin letter, the spans swap into the right places.

How do I get the two spans (and all direct children of <p>) appear in the left-to-right order?

CSS-only solutions preferred.


Solution

  • The reason your current text behaves as it does is that numerals have no "strong direction", and can be embedded in text going in either direction. Regardless of your markup and CSS, the browser is seeing "ااڡوںںطں، ااڡوںںطو 2. ااقونيطن هو قاتل النمر" as a single string, and determining that it should be rendered right-to-left.

    Replacing "2" with a Latin letter (or word) forces the string to be split into three sections where it changes direction.

    To force the browser to treat the two sections of Arabic text in isolation, you can use the bdi (Bi-Direction Isolate) element instead of span for your red and green sections. Note that you don't need to specify the particular direction of any text, the browser will work that out according to Unicode rules.

    .red {
      color: red;
    }
    
    .green {
      color: green;
    }
    <p>Example:
    1. <bdi class="red">ااڡوںںطں، ااڡوںںطو</bdi> 
    2. <bdi class="green">ااقونيطن هو قاتل النمر</bdi>
    </p>

    The CSS-only equivalent of this is unicode-bidi: isolate;, although MDN notes that its direct use is discouraged in favour of elements that imply it (presumably including bdi).

    .red {
      color: red;
      unicode-bidi: isolate;
    }
    
    .green {
      color: green;
      unicode-bidi: isolate;
    }
    <p>Example:
    1. <span class="red">ااڡوںںطں، ااڡوںںطو</span> 
    2. <span class="green">ااقونيطن هو قاتل النمر</span>
    </p>