Get word-spacing width in pixels

1.2k views Asked by At

I'm stuck on how to find the width in pixels of one space between words. For example, if I have a sentence: "The quick brown fox jumps over the lazy dog." and I want the width in pixels of the whitespaces (which will all be the same), is there a formula I could use? This would have to be useable across many different font families and sizes.

I saw that I could set a width using the CSS word-spacing property like the sample below, but I don't want to set it, I want to get the value. Also, I don't want to trim the whitespace either, just calculate the amount of spaces and add their total widths.

p { 
    word-spacing: 5px;
}

Thanks in advance!

3

There are 3 answers

0
Nikita V On

You can simply do this using javascript, to return word-spacing value of the particular element with id="id", if its word-spacing style was specified:

document.getElementById("id").style.wordSpacing;

Here is an example: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_style_wordspacing3

2
styfle On

You need to use window.getComputedStyle if the word-spacing set via CSS.

var ws = document.querySelector('#ws');
var p = document.querySelector('p');
var style = window.getComputedStyle(p);
ws.textContent = style.wordSpacing;
p {
  word-spacing: 5px;
}
<p>The quick brown fox jumped over the lazy dog</p>
<div>The word spacing above is: <b id="ws">0px</b></div>

0
lnamba On

This method ended up working for me. Basically, I needed to make the whole element into a canvas, plug in the font-size/font-family property values and the text I wanted (a space). Then I was able to use measureText() to find the width of a space. https://www.w3schools.com/tags/canvas_measuretext.asp