Jasper
Jasper

Reputation: 2404

How to add/sub to a dynamic variable?

I have a problem with the following code:

@viewport-large: 1440px;
@viewport-medium: 1366px;
@viewport-small: 1280px;

@type: medium;
@setting: ~"@{viewport-@{type}}";
@value: (@setting + 1); // here can't add 1

It will show an error message in the LESS compiler saying: "Operation on an invalid type".

Can anyone tell me why this is the case? What should I do?

Upvotes: 2

Views: 80

Answers (1)

Harry
Harry

Reputation: 89750

The output of Less' CSS escape function (e() or ~"") is a string and you can't add a number to it. This is why the compiler reports Operation on invalid type.

So, instead of doing it that way make use of the double resolution (@@) like in the below code block:

@viewport-large: 1440px;
@viewport-medium: 1366px;
@viewport-small: 1280px;

@type: medium;
@setting: "viewport-@{type}"; /* this won't resolve into 1336px as yet */
@value: @@setting + 1px; /* resolution to 1336px + addition happens here */

In this method, we just form the variable name and set it to the @setting variable (instead of setting a actual px value) and so the real px value's type remains unpolluted. In the next line when we use the double @, Less compiler would try to fetch the value that is held by the variable whose name is same as the value of @setting variable and immediately sum 1px to it instead of converting it to a String.

Note: If you have the Strict Math option (--strict-math) enabled then the addition operation must be wrapped inside extra braces like below. Else, it would plainly output a concatenated value like 1366px + 1px instead of performing the addition and outputting 1367px.

@value: (@@setting + 1px); 

The --strict-math setting is disabled by default but some of your projects could have enabled it.

Upvotes: 2

Related Questions