How Can I increment a variable in LESS css?
Here is the example..
@counter: 1;
.someSelector("nameOfClass", @counter);
@counter: @counter + 1;
.someSelector("nameOfClass", @counter);
The above code snippet will cause this "Syntax Error"
SyntaxError: Recursive variable definition for @counter
Is there a work around for this error? For example is there a notation like @counter++ ?
Thanks..
Not Strictly Possible
See the documentation on LESS variables. Essentially, LESS variables are constants in the scope of their creation. They are lazy loaded, and cannot be "changed" in that way. The very last definition will be the one used for all in that scope. In your case an error will occur, because variables cannot reference themselves.
Consider this example:
The output will be
2
for both:This is because LESS defines the
@counter
with the last definition of the variable in that scope. It does not pay attention to the order of the calls using@counter
, but rather acts much like CSS and takes the "cascade" of the variable into consideration.For further discussion of this in LESS, you might track discussion that occurs on this LESS feature request.
Solution is in Recursive Call Setter for the Local Variable
Seven-phases-max linked to what he believes to be a bug in LESS, but I don't think it is. Rather, it appears to me to be a creative use of recursive resetting of the counter to get the effect desired. This allows for you to achieve what you desire like so (using my example code):
Here is the CSS output:
NOTE: I believe you are not strictly changing a global value here, but rather setting a new local value with each call to
.someSelector
. Whether this is based on buggy behavior or not is questionable, but if so, this solution may disappear in the future. For further comments of the limitations of this method, see the discussion here.