Reputation: 54846
I am trying to set up padding on some \ elements styled as pills, and I want to dynamically change the padding. I know I can do:
@pill-padding-v: 8px;
@pill-padding-h: 15px;
padding:@pill-padding-v @pill-padding-h;
that renders this - and seems to work fine:
padding:8px 15px;
But how can I have LESS add 1px of padding to that?
@pill-padding-v: 8;
@pill-padding-h: 15;
@pill-padding-v: (@pill-padding-v + 1)
@pill-padding-h: (@pill-padding-h + 1)
padding:@pill-padding-vpx @pill-padding-hpx;
The main probelem seems to be adding "px" as part of the variable name I'm getting a compile error. Also I think it is syntactically incorrect to use 8 px
instead of 8px
and that seems to break in browsers, too.
How can I have multiply a pixel width value with LESS Css?
Upvotes: 12
Views: 28347
Reputation: 2168
Aside from add, you can perform any mathematical calculation using LESS this way:
@pill-padding-v: 8;
@pill-padding-h: 15;
element {
/* the numbers I'm multiplying by are arbitrary,
but the value defined in the LESS variable will append
the unit that you multiply it by. */
padding: calc(@pill-padding-v * 3px) calc(@pill-padding-h * 2px);
}
LESS outputs:
element {
padding:calc(24px) calc(30px);
}
Even though it's wrapped in the calc function, it's fine, because the result of the "equation" with no math operator, is that value anyway.
User seven-phases-max offers a good point: you don't need the calc()
function in the LESS. It can be written in LESS as:
element {
padding: (@pill-padding-v * 3px) (@pill-padding-h * 2px);
}
Upvotes: 9
Reputation: 102834
You're right that adding the px
to the variable is causing problems. I actually tried the interpolation syntax and it didn't help, but you should be specifying units anyways in your variables (px
, em
, %
...), like in your first working example.
You said "multiply" but I think you meant "add". There shouldn't be any problem, try this:
@pill-padding-v: 8px;
@pill-padding-h: 15px;
@pill-padding-v: (@pill-padding-v + 1);
@pill-padding-h: (@pill-padding-h + 1);
element {
padding:@pill-padding-v @pill-padding-h;
}
Output should be:
element { padding:9px 16px; }
...although, you might want to just use another variable name or add the 1px right in the style declaration. I don't think re-declaring variables is good practice, and was actually surprised it worked.
Upvotes: 16