htmlcssright-to-leftpre

How to make English text render right-to-left in mixed RTL <pre> tag?


I have the following code:

<html>
<head>
  <style>
    .rtl {
      direction: rtl;
      font-size: 16px;
      font-family: Arial, Helvetica;
    }
  </style>
</head>
<body>
<pre class="rtl">
שלום עולם <b>Right Text</b> ..... <b>Left Text</b> חמש
</pre>
</body>
</html>

JSFiddle: https://jsfiddle.net/xq809b4g/2/

Currently it renders "LeftText" left to שלום עולם, and "RightText" right to "חמש".

Usually, this makes sense, because when I embed English text in RTL text, I'd usually want it to display the English sentence Left-to-Right. However, in this case, because I'm writing a table of contents - The subjects should appear on the right, and the authors should appear on the left.

Can I make it render the opposite way, while still keeping the <pre> tag? In other words, "Right Text" should appear left to "שלום עולם", and "Left Text" right to "חמש".

Current State:

enter image description here

Desired result:

enter image description here


Solution

  • You should make the use of dir attribute.

    When using dir attribute, you can use these values:

    ltr, which means left to right and is to be used for languages that are written from the left to the right.

    rtl, which means right to left and is to be used for languages that are written from the right to the left.

    auto, which lets the user agent decide. It uses a basic algorithm as it parses the characters inside the element until it finds a character with a strong directionality, then applies that directionality to the whole element.

    <pre dir="auto">
      שלום עולם <b dir="ltr">RightText</b> ..... <b dir="ltr">LeftText</b> חמש
    </pre>