For a given element, I appreciate the definiton of 1ch:
the width or more precisely the advance measure of the glyph 0 (zero, the Unicode character U+0030) in the element's font.
What is the best way to calculate the length of 1ch in px with javascript.
I can think of a few approaches such as adding a 0 to the DOM, calculating the width, and then removing it again, or maybe having a permanent hidden 0. But both of these seem hacky, and not very clean.
I am looking for a cleaner approach.
You can use the 2d canvas to do that. But you need to be aware that the rendering between the browser and the 2d canvas might be different.
Also for the DOM approach, you might get different results for an element that contains 0 and an element with the width 1ch:
const c = document.createElement('canvas')
const ctx = c.getContext("2d");
ctx.font = "30px Arial";
console.log('width based on canvas : ' + ctx.measureText('\u0030').width)
console.log('width based on DOM (1ch) : ' + document.querySelector('.element1').getBoundingClientRect().width);
console.log('width based on DOM (0) : ' + document.querySelector('.element2').getBoundingClientRect().width);
.element1 {
font-family: Arial;
font-size: 30px;
width: 1ch;
display: inline-block;
}
.element2 {
font-family: Arial;
font-size: 30px;
display: inline-block;
}
<span class="element1"><span>
<span class="element2">0<span>