3

Is there any easy way to figure out the width of each character in a font? I'm trying to line up two tables of data with data scraped from a website. The issue is that the text in one section of the table might be more than one line, so then I need to make sure the other side needs to be the same number of lines. I'm trying to do this by just calculating the number of lines by dividing the total text length by the line width. My problem is that each character has a different width. Is there any way I'm able to look up how many pixels wide each character in a font is?

For example, I can fit 7 W's and 27 l's if I have the total width set to 100px.

3
  • 1
    Not really sure what the question is but do look into monospaced fonts or tabular lining figures if anything like that is available for the web.
    – lmlmlm
    Commented Mar 5, 2018 at 14:51
  • @TheStrangeQuark - what did you end up doing to solve this problem?
    – youngrrrr
    Commented Aug 7, 2018 at 22:53
  • 1
    @youngrrrr I just ended up using a monospace font Commented Aug 7, 2018 at 22:54

1 Answer 1

1

I realize this question was asked months ago but I just found this javascript/client-side solution, for the programming-inclined, which also should answer your question.

Here's the relevant bit:

In HTML 5, you can just use the Canvas.measureText method (further explanation here).

Try this fiddle:

/**
 * Uses canvas.measureText to compute and return the width of the given text of given font in pixels.
 * 
 * @param {String} text The text to be rendered.
 * @param {String} font The css font descriptor that text is to be rendered with (e.g. "bold 14px verdana").
 * 
 * @see https://stackoverflow.com/questions/118241/calculate-text-width-with-javascript/21015393#21015393
 */
function getTextWidth(text, font) {
    // re-use canvas object for better performance
    var canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas"));
    var context = canvas.getContext("2d");
    context.font = font;
    var metrics = context.measureText(text);
    return metrics.width;
}

console.log(getTextWidth("hello there!", "bold 12pt arial"));  // close to 86

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.