Apply CSS rules based on other rule - RTL specific style

浪子不回头ぞ 提交于 2019-12-22 21:14:07

问题


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.


回答1:


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;
}



回答2:


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
    }
}



回答3:


Probably you are going a little in the wrong direction.

Most of the time, you can achieve this automatically, no need for specific selectors.

Margin, for instance:

Just set it both for left and right margin. The browser will choose the correct one for you

#app {
    width: 300px;
    background: tomato;
    margin: 10px;
}

h1 {
    margin-left: 15px;
    margin-right: 5px;
}
<div id="app" dir="ltr">
  <h1>
    margin left 15
  </h1>
</div><div id="app" dir="rtl">
  <h1>
    margin right 5
  </h1>
</div>


来源:https://stackoverflow.com/questions/48424311/apply-css-rules-based-on-other-rule-rtl-specific-style

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!