Reputation:
If I try to multiply two value with units I get an unexpected error.
$test: 10px;
.testing{
width: $test * $test;
}
result: 100px*px isn't a valid CSS value.
Upvotes: 21
Views: 34575
Reputation: 7810
I have used interpolation in the past when I want to do math with variables, and I think it is the simplest solution. If this doesn't work for you, perhaps it is due to a difference in compilers?
$test: 10px;
.testing{
width: #{$test * 2};
}
In fact width: $test * 2;
compiles to width: 20px
for me, you don't even need to use interpolation for simple math. I am using ember-cli-sass, which uses broccoli-sass-source-maps, which uses node-sass, which wraps libsass, to compile my SCSS to CSS. But it seems to work fine in this jsbin which uses SCSS with Compass.
Where interpolation really helps is if you need to use calc
.
$test: 10px;
.testing{
width: calc(50% + #{$test * 2}); // results in calc(50% - 20px)
}
Upvotes: 51
Reputation: 885
Multiplying units in SASS works like multiplying units in physics / engineering / chemistry / [insert science here].
(see more about this at https://www.sitepoint.com/understanding-sass-units/)
Multiplying two pixel values, will get you px^2, which is an area, not a distance.
What can you do? If you are certain you will be multiplying pixels, use a function and divide by 1 pixel.
$test: 10px;
@function multiply-px($value1, $value2) {
@return $value1 * $value2 / 1px;
}
.testing {
width: multiply-px($test, $test);//100px
}
If you don't know which units you'll be using in advance, you can strip the units from $value2, such that you always get the units of $value1.
(read more on that at https://css-tricks.com/snippets/sass/strip-unit-function/)
$test: 10in;
@function strip-unit($number) {
@if type-of($number) == 'number' and not unitless($number) {
@return $number / ($number * 0 + 1);
}
@return $number;
}
@function multiply-use-first-unit($value1, $value2) {
@return $value1 * strip-unit($value2);
}
.testing {
width: multiply-use-first-unit($test, $test);//100in
}
Upvotes: 22
Reputation: 502
You cannot multiply two px values. Better way of doing it is function, but you have to use add in it to achieve it: -
$test: 10px;
@function calc-width($value1, $value2) {
@return $value1 + $value2;
}
.testing {
width: calc-width($test, $test);
}
Upvotes: -8