SASS: Adding, removing and converting units

Updated . Posted . Visible to the public. Repeats.

Adding a unit

Multiply by 1x the unit:

$number = 13
$length = $number * 1px // => 13px

Removing a unit

Divide by 1x the unit:

$length = 13px
$number = $length / 1px // => 13

Converting a unit

the result of an addition or subtraction between two numbers of different units is expressed in the first member’s unit

Thus, to convert a number, add it to 0 of the desired unit:

$duration: .21s
$duration-in-milliseconds: 0ms + $duration // => 210ms

An example is storing a transition duration as CSS custom property to read it from Javascript. By converting the value like this, you can ensure your Javascript will always get milliseconds, no matter the unit used in CSS.

Dominik Schöler
Last edit
Dominik Schöler
License
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2024-01-18 09:33)