Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a unit to a number in Sass

Tags:

sass

I am trying to create dynamic values, but have failed so far. The created pixel value seems to lose the ability to be used in calculations.

$numericValue: 30;

$pixelValue: $numericValue+px;
// also tried $pixelValue: #{$numericValue}px;

$calc: $pixelValue * 2;
// also tried $calc: unquote($pixelValue) * 2;

This throws an error

Syntax error: Undefined operation: "30px times 2"

like image 488
owzim Avatar asked Mar 20 '13 00:03

owzim


People also ask

Can you do math in Sass?

Unlike other mathematical operations, division in Sass is done with the math. div() function. Although many programming languages use / as a division operator, in CSS / is used as a separator (as in font: 15px/32px or hsl(120 100% 50% / 0.8) ).

How do I concatenate in Sass?

String Operators The single Sass string operator is concatenation. Strings can be concatenated (linked together) using the + operator. If you mix quoted and unquoted strings when concatenating, the result will be whichever is on the left side of the operator.

How do you change a variable value in Sass?

A Sass variable must be initialized with a value. To change the value, we simply replace the old value with a new one. A variable that's initialized inside a selector can only be used within that selector's scope. A variable that's initialized outside a selector can be used anywhere in the document.

What are number operations in Sass?

SASS allows for mathematical operations such as addition, subtraction, multiplication and division. You cannot use incompatible units such as px * px or while adding number with px and em leads to produce invalid CSS. Therefore, SASS will display an error if you use invalid units in CSS.


1 Answers

The trick is to use * 1px when you want to add a unit. Using +px or interpolation (#{$numericValue}px) turns it into a string.

$numericValue: 30;

$pixelValue: $numericValue * 1px;

$calc: $pixelValue * 2;
like image 87
bookcasey Avatar answered Sep 25 '22 21:09

bookcasey