css-calc2
v1.0.2
Published
Parses and resolves a given CSS calc expression
Readme
CSS Calc 2
Parses and evaluates CSS calc() expressions in JavaScript.
Installation
Install via npm:
npm install css-calc2Usage
This package has two exports: parse(), and resolve() which can parse CSS
calc() functions and evaluate them.
Resolving
The resolve() function evaluates a CSS calc() expression and returns a
simplified result.
import Calc from "css-calc2"
const result = Calc.resolve("calc(10px + 2px)")
console.log(result) // => "12px"You can also pass already parsed expressions:
const ast = Calc.parse("calc(50% - 10%)")
const result = Calc.resolve(ast)
console.log(result) // => "40%"Supported operations
The evaluator supports standard CSS math operators:
+addition-subtraction*multiplication (number × length/percentage where valid)/division (number division only, per CSS rules)
It also supports nested expressions:
Calc.resolve("calc(5px + (10px - 2px))")
// => "13px"And functional min/max:
Calc.resolve("calc(min(10px, 20px) + 5px)")
// => "15px"Note: Invalid combinations of units (e.g.
px+%) will not be resolved and will either throw or remain unresolved depending on configuration.
Parsing
The parse() function transforms a CSS calc expression into a structured token
representation that can be inspected or reused.
import Calc from "css-calc2"
const ast = Calc.parse("calc(10rem + 2rem)")The ast variable will have the following payload:
;[
{
type: "number",
value: 10,
unit: "rem",
},
{
type: "number",
value: 2,
unit: "rem",
},
{
type: "operator",
value: "+",
},
]License
This software is free to use under the ISC license. See the LICENSE file for license text and copyright information.
