MDN self-hosted library · e01.org

CSSNumericValue: parse() static method

Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.

js
const length = CSSNumericValue.parse("42.0px");
console.log(length.constructor.name); // "CSSUnitValue"
console.log(length.value); // 42
console.log(length.unit); // "px"

const percentage = CSSNumericValue.parse("50%");
console.log(percentage.unit); // "percent"
js
const sum = CSSNumericValue.parse("calc(50% + 10px)");
console.log(sum.constructor.name); // "CSSMathSum"
console.log(sum.toString()); // "calc(50% + 10px)"

const simplified = CSSNumericValue.parse("calc(1px + 2px)");
console.log(simplified.toString()); // "calc(3px)"
js
try {
  CSSNumericValue.parse("auto");
} catch (e) {
  console.log(e.name); // "SyntaxError"
}