Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply CSS rules based on other rule - RTL specific style

Tags:

Presentation

I'm trying to build a web site available in multiple cultures, with different reading direction.

To do so, I simply add the dir="rtl" attribute on my root HTML element.

My issue is that I have some CSS rules that are specific to one direction or the other (margins or paddings, most of the times).

Unsuccessful try with attribute selector

I though that I could simply use the attribute selector but the dir attribute is only set on the root element, so this wouldn't work :

selector {
  &[dir="ltr"] {
    // LTR specific
  }

  &[dir="rtl"] {
    // RTL specific
  }
}

For instance, on this demo, the title should have a margin of 5px on the right if the application is in rtl or on the left if it's in standard ltr.

Other idea

I've noticed that the direction is rightfully set at rtl, is there a way to use that rule within a CSS or Sass selector ?

Edit and precisions

It seems that I've forgotten an important point. I'm building the web site using Vue.js, the dir attribute is bind in the main component (App) and the RTL/LTR specific CSS rules can be in the same component or in other self-contained component.

like image 936
Thomas Ferro Avatar asked Jan 24 '18 14:01

Thomas Ferro


2 Answers

Following your css code you could do this with SASS at-root directive DEMO. So this:

#app {
  width: 300px;
  height: 100px;
  border: 1px solid red;

  h1 {
    @at-root {
      [dir="rtl"]#{&} {color: green}
    }

    @at-root {
      [dir="ltr"]#{&} {color: red}
    }
  }
}

It will compile to this css.

#app {
  width: 300px;
  height: 100px;
  border: 1px solid red;
}
[dir="rtl"]#app h1 {
  color: green;
}
[dir="ltr"]#app h1 {
  color: red;
}
like image 130
Nenad Vracar Avatar answered Oct 12 '22 23:10

Nenad Vracar


You could style everything LTR, and only adjust some elements styling for RTL. Might this work for you?

[dir="rtl"] {
    &selector {
        // RTL specific
    }

    &selectorN {
        // RTL specific
    }
}
like image 33
Brainfeeder Avatar answered Oct 13 '22 00:10

Brainfeeder