Less / css - targeting dom elements with data attributes with value (n)

I have a navigation menu that assigns an array of colors to menu items based on their depth in the menu / taxonomy hierarchy. So, for example, all the top-level menu items get the color black, the next level turns red, the next level turns green, etc., And since the hierarchy goes very deep, I would like to target using math, it’s kind of like css can target nth-child. However, I cannot use nth-child because these container elements ("browse level") are dynamically added and removed from the DOM (they are not all in the DOM at the same time), so I target data attributes.

So here is the CSS:

.browse-level[data-level="1"] li a {
  background: @level1;
}

.browse-level[data-level="2"] li a {
  background: @level2;
}

.browse-level[data-level="3"] li a {
  background: @level3;
}

.browse-level[data-level="4"] li a {
  background: @level4;
}

... etc.

8 ( ). ( LESS CSS) ?

+5
1

@level1: #aaa;
@level2: #bbb;
@level3: #ccc;
@level4: #ddd;
@level5: #eee;
@level6: #fff;
@level7: #000;
@level8: #111;

.mymixin(@lev) when ( @lev > 0 ) {
  @ruleNameA: e('.browse-level[data-level="');
  @ruleNameB: e('"] li a');
  @{ruleNameA}@{lev}@{ruleNameB} {
    @bgAux: e('level@{lev}');
    background: @@bgAux ;
    }
  .mymixin( @lev - 1 ) ;
}

.mymixin(8);

http://less2css.org/ :

.browse-level[data-level="8"] li a {
  background: #111111;
}
.browse-level[data-level="7"] li a {
  background: #000000;
}
.browse-level[data-level="6"] li a {
  background: #ffffff;
}
.browse-level[data-level="5"] li a {
  background: #eeeeee;
}
.browse-level[data-level="4"] li a {
  background: #dddddd;
}
.browse-level[data-level="3"] li a {
  background: #cccccc;
}
.browse-level[data-level="2"] li a {
  background: #bbbbbb;
}
.browse-level[data-level="1"] li a {
  background: #aaaaaa;
}
+5

All Articles