javascript – Language conditional CSS

Question:

When a CSS stylesheet is included, the media query can be specified directly in the link tag with the condition that must be met for those styles to be applied:

<link media="(max-width: 480px)" href="moviles.css" />

Is there something similar but for the browser language? Or at least for the case of right-to-left text (ex: Arabic)? Something like this:

<link media="(lang: ar)" href="rtl.css" />

Where the stylesheet would only contain things like:

.flota-izquierda { float: right; }
.float-derecha { float:left; }
.izquierda { text-align: right; }
.derecha { text-align: left; }

....

I know I could use LESS / SASS to simplify my source code, but the CSS generated on compiling would still be complex and large anyway, because when expanded it would look like:

 [lang=ar] .flota-izquierda { float: right; } [lang=ar] .float-derecha { float:left; } [lang=ar] .izquierda { text-align: right; } [lang=ar] .derecha { text-align: left; } ....

I would prefer an answer that only uses HTML and CSS, but if there is no option, JavaScript would also be a possibility to consider.

Answer:

An alternative way I can think of is by using a bit of javascript.

  1. You get the computed value of the direction property of the <body>
  2. You add the necessary CSS by code.

Example:

// esto obtiene ltr o rtl 
var dir = window.getComputedStyle(document.body).direction
 
// agregamos archivo-ltr.css o archivo-rtl.css
var link = document.createElement( "link" );
link.href = '/ruta/al/archivo-' + dir + '.css';
link.type = 'text/css';
link.rel = 'stylesheet';

document.getElementsByTagName('head')[0].appendChild(link);
Scroll to Top