Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

less / css - targeting dom elements with data attributes with a value of (n)

I have a navigational menu which assigns an array of colors to menu items based on their depth within a menu hierarchy / taxonomy. So, for example, all top level menu items get a color of black, next level gets red, next level gets green, etc, and because the hierarchy goes very deep, I'd like to target them using math, sort of the way that css can target nth-child. However, I can't use nth-child because these container elements ('browse-level') are dynamically added and removed from the DOM (they're not all in the DOM at the same time) which is why I'm target data attributes.

So here's 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

There are 8 color values (after which the sequence would repeat). Can I (using LESS or plain CSS) shorten this code?

like image 289
mheavers Avatar asked Apr 11 '13 15:04

mheavers


1 Answers

I would go with

@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);

According to http://less2css.org/ it produces:

.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;
}
like image 82
norteo Avatar answered Sep 24 '22 22:09

norteo