Search code examples
htmlcsslocalizationright-to-leftleft-to-right

How to mix RTL and LTR text directions in the same <option> element?


I am implementing a RTL interface. All components and texts are RTL but numbers which are LTR.

I use <span dir="ltr"> elements to insert LTR texts into the main RTL texts.

It works in the most of the cases but not for a <option> element:

<div dir="rtl">
  <select>
    <option>One amount <span dir="ltr">15.000</span> coins</option>
    <option>Other amount <span dir="ltr">19،000</span> coins</option>
  </select>
</div>

It is not working.

Here there is a JSfiddle to play with: https://jsfiddle.net/fguillen/2hngzv3d/


Solution

  • At the beginning, I thought it is a bug (something related to unicode-bidi: bidi-override), but when I tried on IE, Edge, and Firefox they all gave kinda the same result. This gave me enough evidence that this is a normal behavior. I Looked around here and there, and found what's wrong.

    The <option> tag

    The option tag is somehow special. From Mozilla <option> documentation, it states that you can only write text inside it. This means any tag you write inside <option> tag, it will be ignored by the browser parser, and this is exactly why your<span> tag was ignored. See the image below from Firefox DOM inspector. It also worth mentioning that smartphones displays select option in a spinner instead of a combo box (of course you can override this). The means it is really meaningless to have any thing other than text within the <option> tag.

    enter image description here

    Understanding unicode-bidi Attribute

    RTL text, by default, is smart enough to handle embedded LTR text by applying the Unicode Bi-directional Algorithm. If you override the algorithm by using bidi-override, you will be responsible for handling any LTR text within RTL text.

    This means that inside the element, reordering is strictly in sequence according to the direction property; the implicit part of the bidirectional algorithm is ignored. - (Mozilla Documentation)

    Now in your case, you cannot place a <span> inside <option> because it is invalid HTML nor use an &LRM; character because you disabled bidi algorithm.

    The Solution

    The only solution I can think of is

    • Step 1: Remove bidi-override.
    • Step 2: Use RTL text instead of English text.

    See this fiddler: https://jsfiddle.net/61dvmsnn/

    Moral of the story

    Unless you are trying to create a mirror effect, never use bidi-override. Never disable bidi algorithm. Also, always use RTL text (e.g. Arabic, Hebrew, Farsi...) when testing inside RTL elements. Let the bidi algorithm works its magic.