MerlynCooper MerlynCooper - 6 months ago 17
CSS Question

LESS CSS nested loops for header elements

first post,

My question is this,

Is it possible to do a less loop for iterated elements (rather than iterated classes/ids) and if so what am I doing wrong and how would I do it otherwise?

.generate-columns(4);

.generate-columns(@n, @i: 1) when (@i =< @n) {
.column-@{i} {
width: (@i * 100% / @n);
}
.generate-columns(@n, (@i + 1));
}


Above is the example generic loop show on the less features page,
It's really interesting I feel so I wondered what circumstance I could use it for.
I thought that autogenerating header element fontsizes for different header sizes would be perfect; below is my attempt

.headers-generator(6);

.headers-generator(@n, @i : 1) when (@i =< @n)
{
h@{i}{
font-size: (2em - ((@i - 1) * 0.2)em);
}
.headers-generator(@n, (@i + 1));
}


Below is the expected output

h1
{
font-size: 2em;
}
h2
{
font-size: 1.8em;
}
h3
{
font-size: 1.6em;
}
h4
{
font-size: 1.4em;
}
h5
{
font-size: 1.2em;
}
h6
{
font-size: 1em;
}


I am using Visual Studio 2012 and Web Essentials,
Web Essentials' error for this LESS is "missing a colon between property and value" and it also tells me that the
@i
and
@n
inside the curly brackets are "undeclared".

Input much appreciated.

Answer

This mixin will work in LESS 1.6+. The em at the end of the font-size calculation was kicking up an error and is not necessary as em units are already being used in the calculation.

.headers-generator(@n; @i : 1) when (@i =< @n)
{
  h@{i} {
    font-size: (2em - (@i - 1) * 0.2);    
  }

  .headers-generator(@n; (@i + 1));
}

.headers-generator(6);