hguser
hguser

Reputation: 36018

Does LESS support this syntax ?

I am curently using LESS. Since I use CSS sprites, I wonder if LESS support this kind of syntax:

icon{x}{
  background-position:-10px -10*{x}px;
}

Since I have to create this CSS style:

icon1{
  background-position:-10px -10px;
}
icon2{
  background-position:-10px -20px;
}
icon3{
  background-position:-10px -30px;
}
.................

Upvotes: 0

Views: 108

Answers (1)

Pierre Espenan
Pierre Espenan

Reputation: 4066

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>

Upvotes: 1

Related Questions