The maths doesn't stop there. CSSNumericValue
s come with their own set of operations that can be performed on all numeric values. What operation you use and with what values, depends on what is returned. Let's take a look at all the methods and a few examples of each. As these methods are available on the CSSNumericValue
super class they can take a unit or a sum.
add
let sum = CSS.px(54).add(CSS.px(30));
// Returns: CSSUnitValue {value: 84, unit: "px"}
In the above example we are using the same unit, and so a direct addition takes place and a CSSUnitValue
is returned. If we use varying units, a CSSMathValue
is returned.
let add = CSS.px(54).add(CSS.em(2.4));
add.toString() // calc(54px + 2.4em)
sub
let sub = CSS.mm(300).sub(CSS.mm(210));
// Returns: CSSUnitValue {value: 90, unit: "mm"}
As with add
above, if we use different units a CSSMathValue
is returned
let sub = CSS.cm(5).add(CSS.mm(90));
sub.toString() // calc(5cm + -90mm)
mul
Notice here you can pass in just a number to the multiply function. A CSSNumericValue
would work as well. Differing values will return a CSSMathValue
.
let mul = CSS.em(1.2).mul(1.4);
// Returns: CSSUnitValue {value: 1.68, unit: "em"}
div
As with mul
you can enter a number or a CSSNumericValue
. Different units return a CSSMathValue
let div = CSS.turn(1).div(2);
// Returns: CSSUnitValue {value: 0.5, unit: "turn"}
min
min
returns the lowest value, and you can input as many values as you please. If the units differ a CSSMathMin
type is returned with the values and units that have been used.
let min = CSS.px(500).min(CSS.px(400), CSS.px(200));
// Returns: CSSUnitValue {value: 200, unit: "px"}
min = CSS.em(1.2).min(CSS.rem(1.4));
min.toString() // min(1.2em, 1.4rem)
max
Same as min
, however it returns the maximum value in the list, or if the units differ, a CSSMathMax
type
let max = CSS.pt(50).max(CSS.pt(90), CSS.pt(10));
// Returns: CSSUnitValue {value: 90, unit: "pt"}
max = CSS.px(500).max(CSS.percent(60));
max.toString() // max(500px, 60%)
Conversion & Comparison
Maths methods are pretty useful, so is a way to convert units on the fly. We can do that with the to
method.
to
It only allows us to convert absolute units. (Unfortunately not relative ones at this time).
// inches to centimetres
const cm = CSS.in(2).to('cm');
// Returns: CSSUnitValue {value: 5.08, unit: "cm"}
equals
Another very interesting bit of functionality. We can test to see if one value is equal to another with just one method.
const fontSize = CSS.em(1.2);
CSS.em(1.2).equals(fontSize); // true
When using these latter two pieces of functionality together we can do some clever stuff, like convert degrees to radians and check it within our code, without having to know the precise radian value, which is always a bit trickier to remember than degrees.
const radians = CSS.deg(90).to('rad');
const check = CSS.deg(90).equals(radians.to('deg')); // true
Let's have a look at an example using what we have learnt so far