Search code examples
htmlcssasp.net

Automactially set direction and text-align based on rtl or ltr languages


We can set direction property for body tag to instruct direction either rtl to ltr. Similarly we can set text-align properties for individual elements.

Is there any way to minimize or centralize coding efforts to design an application which can support both LTR(English) and RTL(Arabic) languages. Its OK, I can write separate css for both directions, but what could be the best way to switch between these css(e.g, in master page load event)?

There also comes an exceptional case, like in English language I need first column of grid to display as text-align:left (it contains text), but remaining columns should be display with text-align:left, because that columns contains numeric values. Similarly the case will be reverse for Arabic language.


Solution

  • You can target elements under <body> where direction is set to a specific value like so:

    body span { text-align: left } /* default value */
    body[direction="rtl"] span { text-align: right } /* override for rtl languages */
    

    However if you have a lot of elements using text-align, this can get tiresome. Perhaps you could make a class for text-align using the same method:

    .aligned { text-align: left }
    body[direction="rtl"] .aligned { text-align: right }
    

    Finally, for more complex situations you may find RTLCSS useful:

    RTLCSS is a framework for converting Left-To-Right (LTR) Cascading Style Sheets(CSS) to Right-To-Left (RTL).