I've got a .less stylesheet with the following construct:
@width:600;
.some-style
{
width:@{width}px;
}
and this gives the following error:
Expected '}' on line x in file '..\styles.less'
I need those braces, because I need to distinguish the variable from the following px
suffix (@widthpx
doesn't work because then it looks for a variable called widthpx
). And I can't use a space because 600 px
isn't valid css. Using parentheses instead of curly braces doesn't work either.
What am I doing wrong here?
Update: I installed the latest version of .less from the Package Manager, and now it works a little better, but with a fatal flaw:
width:@(width)px; <--note the parentheses
now compiles, but emits this CSS:
600 px <--note the space, which is invalid CSS, thus useless.
Solved: ScottS pointed me to the solution. In addtion to his two methods, it looks like the compiler can do math on string. So this works:
@width:600px;
.some-style
{
width:@width / 2; <--correctly emits "300px"
}
So if I understand correctly, you want to give the width
a value but without any units, and assign the units at the time of the call. I'm not sure why you would want to do that, but there are two ways that would work:
ONE: make the width
a string and then do a string interpolation:
@width: '600';
.some-style
{
width: ~'@{width}px';
}
TWO: multiply by 1px
:
@width: 600;
.some-style
{
width: @width * 1px;
}
I've left the above answers in place for a case of "unitless" numbers and how to add the unit later (as the question appeared to be at first). However, based on your comment let me explain why @width: 600px
works. LESS does not see that as a string (as you mention you view it). Rather, it sees it as a number with units. To LESS 600px
is not the string of characters (unless it is wrapped in quotes), but the number 600
in units of pixels
. This is why it can do operations on it just fine, without you having to worry about it. It can do so whether those units are em
or %
or any other valid CSS unit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With