Page 1 of 1

Calculate number of characters per line that fit into Div

Posted: 31 Jan 2015, 09:10
by PloMar
Hello all
Anyone know how to calculate the number of characters that will fill one line of a div with a fixed width (for example 200px), using JavaScript?
Or, getting the line width (in pixels) for 25 characters?

Calculate number of characters per line that fit into Div

Posted: 31 Jan 2015, 09:45
by MarPlo
Hi,
You can use this formula to get the width of the line for a given number of characters (CPL):

Code: Select all

Width = CPL * (font-size / font-constant)
- CPL = number of characters per line.
- font-constant = a constant specified to each font.

Example with "font-family: 'Arial', sans-serif;" (font-constant = 1.91), and "font-size: 18px".

Code: Select all

<script>
var cpl = 25;
var fs = 18;
var fc = 1.91;

var width = Math.ceil(cpl * (fs / fc));

// Test
alert(width); // 236
/* 25 characters with font-size 18px and font-family Arial need 236px line-width */
</script>
- Anyway, it's not very accurate because some characters are wider than others. But is accurate for Monospace font, like "Courier New".

This formula when you have the Width and you want to get the number of characters (CPL) that fit on a line with that Width:

Code: Select all

CPL = Width / (font-size / font-constant)
Example with line of 180 pixels, "font-family: 'Courier New';" (font-constant = 1.64), and "font-size: 16px".

Code: Select all

<script>
var width = 180;
var fs = 16;
var fc = 1.64;

var cpl = Math.floor(width / (fs / fc));

// Test
alert(cpl);
/* 18 characters in a 180 pixels line-width, font-family Courier New, size 16px */
</script>
Here's some fonts with their constant:
- Serif Fonts:
American Typewriter — 2.14
Baskerville — 2.14
Georgia — 1.91
Times New Roman — 2.21

- Sans-serif Fonts:
Arial — 1.91
Calibri — 2.1
Helvetica Neue — 1.9
Lucida Grande — 1.91
Tahoma — 1.91
Trebuchet MS — 2.11
Verdana — 1.73

- Monospace Font:
Courier New — 1.64