3

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!

styfle
  • 22,361
  • 27
  • 86
  • 128
lnamba
  • 1,681
  • 3
  • 18
  • 26

3 Answers3

2

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

Nikita V
  • 367
  • 4
  • 9
1

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

lnamba
  • 1,681
  • 3
  • 18
  • 26
0

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>
styfle
  • 22,361
  • 27
  • 86
  • 128
  • Nice! I actually wanted to see if I could do this without setting the `word-spacing` property though. – lnamba Sep 08 '17 at 15:27
  • I don't believe it's possible to get a value that isn't there. Maybe you could update your question with your html, css, and js. – styfle Sep 08 '17 at 18:13