epeleg epeleg - 1 year ago 70
CSS Question

how to base a css rule on inherited value of dir attribute

I know I can use

to select elements that have a dir attribute with a specific value.

so I can define for example

[dir='ltr'] .float-end {float:right}
[dir='rtl'] .float-end {float:left}

to get a
class that floats right or left when inside an element with ltr or rtl respectively.

The problem starts when I have an ltr sub part of a document that is rtl.

<div dir="rtl">
<div dir="ltr">
<div class="float-end"></div>

What happens is that both rules match... and I only want to match the 'ltr' case in this scenario.

The problem gets worse if I want to create classes such as
to provide
and vice versa depending on context.

Would result in both
being applied....

I am looking for suggestions on how to overcome this.

Is there a way to depend on the nearest value of an attribute of any given type of element?

This is all done within the context of LESS mixins if it helps some how...


Answer Source

O.k. So having learned that what I expected just does not work (at least not as of now [June 2014]), I ended up with the following LESS based solution:

// provide a mixin to use two different rule sets depending on the current direction.

.ltr(@ltrRules) {
  body[dir="ltr"] & , body[dir="rtl"] [dir="ltr"] &, body[dir="rtl"] [dir="ltr"]&  { @ltrRules(); }

.rtl (@rtlRules) {
  body[dir="rtl"] & , body[dir="ltr"] [dir="rtl"] &, body[dir="ltr"] [dir="rtl"]& { @rtlRules(); }

.bidi(@ltrRules,@rtlRules) {

// padding
// ------------------------------------------
.padding-start(@p) { 
   { padding-left: @p } ,
   { padding-right: @p }

so using .padding-start(10;) on some SELECTOR

.my .selector {

will eventually generate the following CSS:

body[dir="ltr"] .my .selector,
body[dir="rtl"] [dir="ltr"] .my .selector,
body[dir="rtl"] [dir="ltr"].my .selector {
  padding-left: 10px;

body[dir="rtl"] .my .selector,
body[dir="ltr"] [dir="trl"] .my .selector,
body[dir="ltr"] [dir="trl"].my .selector {
  padding-right: 10px;

The compromise is that I can not change the direction multiple times going into the depth of the document and that the initial seeing of the direction must be on the body tag.

That siad, if for some absurd reason I WILL get to some point in the future when I will have to change the dir more then twice I can just use the same method and add handling for body[dir="ltr"] [dir="rtl"] [dir="ltr"] & and so on...

With some luck in a few years someone will understand that it is important to add the semantics of start and end that get interpreted as left and right respectively in LTR contexts and vice versa in TRL contexts making all my macros redundant... [as has already been done in text-align for example].

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download