Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

156
Vistas
How do I calculate the length of 1ch in pixels with javascript?

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.

My question

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.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda