Search code examples
javascriptjqueryhtmlcssright-to-left

Break <span>s into next line starting from the left (rtl language)


I have some spans. They form a sentence:

<span dir="rtl"> word4 </span> 
<span dir="rtl"> word3 </span>
<span dir="rtl"> word2 </span>
<span dir="rtl"> word1 </span>

It's written in a language which goes from right to left. So the last span contains the very first word. Now everything is displayed correctly as long as the sentence is displayed in one single line.

HOWEVER: When the sentence breaks, it will break the usual way, which means that what is the first word of the sentence, is now in the next line.

How can I make my spans break down on the left, so that the first span moves down into the next line first?


Solution

  • Using flex:

    <div class="container">
      <span> word1 </span>
      <span> word2 </span>
      <span> word3 </span>
      <span> word4 </span>
    </div>
    

    and the css style is like this:

    .container {
        display: -ms-flexbox;
        display: -webkit-flex;
        display: flex;
        -webkit-flex-direction: row-reverse;
        -ms-flex-direction: row-reverse;
        flex-direction: row-reverse;
        -webkit-flex-wrap: wrap;
        -ms-flex-wrap: wrap;
        flex-wrap: wrap;
        }
    

    it should be noted that the above css makes all Spans align to right. if you want to align the Spans to the left, add this statements to the ".container" css class:

    -webkit-justify-content: flex-end;
    -ms-flex-pack: end;
    justify-content: flex-end;
    

    Turning this into a stack snippet, with a width that will force wrapping and a background to see the container gives this:

    .container {
                display: -ms-flexbox;
                display: -webkit-flex;
                display: flex;
                -webkit-flex-direction: row-reverse;
                -ms-flex-direction: row-reverse;
                flex-direction: row-reverse;
                -webkit-flex-wrap: wrap;
                -ms-flex-wrap: wrap;
                flex-wrap: wrap;
                }
    .a-block-to-force-warping{
                max-width: 10em;
                background-color: red;
    }
    <div class="a-block-to-force-warping">
    <div class="container">
        <span> word1 </span>
        <span> word2 </span>
        <span> word3 </span>
        <span> word4 </span>
    </div>
    </div>