Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

160
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!