Kensing
Kensing

Reputation: 107

Monospace font string width

I have an input element which feeds into a list element, both with the same monospace font. char_width_test is the ID of a span element that contains 1 character with the same monospace font. I check this width and multiply with the length of strings given in the input field to calculate the width of the list item that is created from that string.

var ul = document.getElementById('posts_list');
var li = document.createElement('li');
var txt = document.createTextNode(str);
ul.appendChild(li);
li.innerHTML = str;

li.style.width = (($("#char_width_test").width() * str.length)) + 'px';

Above code produces widths that have more whitespace the longer the strings. There seems to be some variable affecting the width that I'm missing?

Upvotes: 1

Views: 737

Answers (1)

Alex Mcp
Alex Mcp

Reputation: 19315

There is kerning between characters, so the width of one character isn't quite what you want to multiply.

http://en.wikipedia.org/wiki/Kerning

Once you've determined the width of one letter and the amount of kerning, you'll need n * char_width + (n - 1) * kerning_width to be more accurate.

I might try something like kerning = width_of_two_characters - (width_of_one_character * 2) if there is no padding or margin on the span. See how that works out.

Upvotes: 1

Related Questions