Is it possible ?
Unfortunately, I think it's not. LESS is a compiled language and doesn't support (yet ?) iteration control structures like while()
or for()
.
To begin an answer, I would write the following HTML code :
<div id="1" class="icon"></div>
<div id="2" class="icon"></div>
<div id="3" class="icon"></div>
With the following LESS code :
.dynamic-background(@i)
{
background-position: -10px (-10px * @i);
}
@var: `document.getElementsByClassName('icon')[2].id`;
.icon
{
.dynamic-background(@var);
}
Which would result as the following CSS code :
.icon
{
background-position: -10px -30px;
}
But as you can see, this code is dynamic for only one element by page, due to the [x]
on the result of getElementsByClassName
. Maybe there is an additional trick that I'm missing there, though.
Alternative solution
Maybe could you just use Javascript :
<script type="text/javascript">
var elems = document.getElementsByClassName('icon');
for (var i=0; elems[i]; i++)
elems[i].style.backgroundPosition = '-10px -'+elems[i].id*10+'px';
</script>
Which results in the following:
<div id="1" class="icon" style="background-position: -10px -10px;"></div>
<div id="2" class="icon" style="background-position: -10px -20px;"></div>
<div id="3" class="icon" style="background-position: -10px -30px;"></div>