This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
The convertToSpecifiedUnits() method of the SVGLength interface allows you to convert the length's value to the specified unit type.
This function will:
unitType property to the given unit typevalueInSpecifiedUnits and valueAsString properties so the length value is represented in the given unit typeconvertToSpecifiedUnits(unitType)
unitTypeA constant representing the unit type to which the length's value should be converted. This must be one of the constant values defined for the unitType property, with the exception of SVG_LENGTHTYPE_UNKNOWN.
SVGLength.SVG_LENGTHTYPE_NUMBER: convert to unitless numberSVGLength.SVG_LENGTHTYPE_PERCENTAGE: convert to percentageSVGLength.SVG_LENGTHTYPE_EMS: convert to em unitsSVGLength.SVG_LENGTHTYPE_EXS: convert to ex unitsSVGLength.SVG_LENGTHTYPE_PX: convert to pixelsSVGLength.SVG_LENGTHTYPE_CM: convert to centimetersSVGLength.SVG_LENGTHTYPE_MM: convert to millimetersSVGLength.SVG_LENGTHTYPE_IN: convert to inchesSVGLength.SVG_LENGTHTYPE_PT: convert to pointsSVGLength.SVG_LENGTHTYPE_PC: convert to picasNone (undefined).
// Get an SVGLength object
const svg = document.querySelector("svg");
const length = svg.createSVGLength();
// Set a length value in centimeters
length.valueAsString = "0.5cm";
// Convert the length to millimeters
length.convertToSpecifiedUnits(SVGLength.SVG_LENGTHTYPE_MM);
console.log(length.unitType); // Output: 7 (SVG_LENGTHTYPE_MM)
console.log(length.valueInSpecifiedUnits); // Output: 5
console.log(length.valueAsString); // Output: "5mm"
| Desktop | Mobile | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Opera | Safari | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | WebView Android | WebView on iOS | |
convertToSpecifiedUnits |
1 | 12 | 1.5 | ≤12.1 | 3 | 18 | 4 | ≤12.1 | 1 | 1.0 | 4.4 | 1 |
© 2005–2025 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/SVGLength/convertToSpecifiedUnits