CSS conditional on language

7

When a CSS stylesheet is included, you can specify the media query directly on the link tag with the condition that must be met for those styles to apply:

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

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

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

Where the style sheet 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 when compiling would still be complex and large anyway, because by expanding 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.

    
asked by Alvaro Montoro 26.09.2016 в 18:41
source

2 answers

6

An alternative way that occurs to me is using a bit of javascript.

  • You get the computed value of the property direction of <body>
  • 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);
        
    answered by 26.09.2016 / 19:56
    source
    2

    You can do it like this:

    p:lang(it) { 
        background: yellow;
    }
    

    In that case I would paint the panel yellow when the language is Italian.

    Another way to do it would be like this:

    /* Ingles (default language)*/
    [data-i18n]::before {
       content: attr(data-i18n);
    }
    /* Aleman */
    [data-i18n-de]:lang(de)::before {
       content: attr(data-i18n-de);
    }
    /* Ruso */
    [data-i18n-ru]:lang(ru)::before {
       content: attr(data-i18n-ru);
    }
    

    And when declaring the panel you indicate the value that would be charged in each case:

    <p id="hello" data-18n="Hello" data-i18n-de="Hallo" data-i18n-ru="Привет"><p>
    

    There are other ways, you can look at the following link:

    link

        
    answered by 26.09.2016 в 19:00