Precalc
Simplify CSS equations with mixed units and wrap them in calc.
const calc = const num = 5 // '45px' (calc is not required) // 'calc(25% + 20px)` // 'calc(20vh - 10px)'
API
The primary function. It supports currying.
calc([options], input)
-
options
(object) - optional-
units (array<string> | boolean) - default: false
-
validate the unit types in the input equation
-
array - if the equation has units that are not in the array, throw an error
-
true - valdate against vh, vw, px, %, em, rem
-
false - do not validate units
-
-
throws (boolean) - default: true
-
throw errors for malformed equations
-
when false,
eq
andcalc
return null for invalid input
-
-
-
input
(string) - css equation- supported operators: + - / *
// this works... // and this works... // and this...calc = // ...works too! // evaluates with throws: false
eq([options], input)
just like calc
, but without the word "calc" in the output
const num = 5 // '45px' // '25% + 20px`
wrapInCalc(input)
wraps the input with "calc" if necessary
input
(string) - css equation
// '50%' // 'calc(50% + 25px)'
NOTE:
calc
is just shorthand for eq
and wrapInCalc
together:
const calc =
Example
generating 16x9 height and width
const columns = 2const ratio = '9 / 16' let width = // input: '20vw * 2 + 10px * 2'// output: '40vw + 20px' const height = // input: '(40vw + 20px) * (9 / 16)'// output: 'calc(22.5vw + 11.25px)' width = // input: '40vw + 20px'// output: 'calc(40vw + 20px)'
To see examples of valid input, check index.test.js
Input Errors
-
Non-matching parentheses
-
Letters or % character with no preceding number
-
Unsupported unit types (unless
options.units
is false) -
Input with chars that are not + - * / % ( ) digits or letters
-
Adding or subtracting a number with units to a number without units
-
Multiplying two numbers that both have units
-
Dividing by a number with units
-
Dividing by zero