CSSNumericValue: to() method
Limited availability
This feature is not Baseline because it does not work in some of the most widely-used browsers.
Want more browser support for this feature? Tell us why.
Note: This feature is available in Web Workers.
The to() method of the CSSNumericValue interface converts the CSSNumericValue to a CSSUnitValue in the specified unit.
Syntax
to(unit)
Parameters
unit-
A string naming the unit to convert to, such as
"px","deg", or"s". Use"number"for a plain number, and"percent"for a percentage.
Return value
A new CSSUnitValue whose unit is unit.
Exceptions
SyntaxErrorDOMException-
Thrown if
unitisn't a valid CSS unit. TypeError-
Thrown if:
- The
CSSNumericValueis a calculation whose terms can't be combined into a single value. For example,calc(1px + 1em)can't be combined, because the size of anemdepends on the font size. A length multiplied by a length, such ascalc(1px * 2px), can't be combined either, because it can't be written in a single unit. - The value can't be converted to
unit. For example, you can't convertpxtos, orpxtoem.
- The
Description
The method can only convert between units that have a fixed relationship to each other. These are:
- Absolute lengths:
px,cm,mm,Q,in,pt, andpc - Angles:
deg,rad,grad, andturn - Times:
sandms - Frequencies:
HzandkHz - Resolutions:
dpi,dpcm, anddppx
Relative units such as em, vw, and % can't be converted to any other unit, because their size depends on the page, such as the font size or the size of the element's container.
If the CSSNumericValue is a calculation, the method first combines its terms.
This works if every term can be converted to a single unit: for example, calc(100px + 1in) can be converted to 196px, and max(1px, 1in) to 96px.
It fails if the terms can't be combined, such as 1px and 1em, or if combining them gives units multiplied together, such as a length multiplied by a length.
Examples
>Converting a value to another unit
console.log(CSS.in(1).to("px").toString()); // "96px"
console.log(CSS.turn(1).to("deg").toString()); // "360deg"
console.log(CSS.ms(500).to("s").toString()); // "0.5s"
Converting a calculation
When all the terms of a calculation can be converted to the same unit, to() combines them into a single value:
const sum = CSS.px(100).add(CSS.in(1));
console.log(sum.toString()); // "calc(100px + 1in)"
console.log(sum.to("px").toString()); // "196px"
Values that can't be converted
Converting a sum that includes a relative length, or converting a length to a time, throws a TypeError:
try {
CSS.px(1).add(CSS.em(1)).to("px");
} catch (e) {
console.log(e instanceof TypeError); // true
}
try {
CSS.px(10).to("s");
} catch (e) {
console.log(e instanceof TypeError); // true
}
Specifications
| Specification |
|---|
| CSS Typed OM Level 1> # dom-cssnumericvalue-to> |