I'm looking to display only 1 line of text from a source where characters range from 0-255. I do not want the text to exceed 1 line, and if it would, I want to truncate and display "...". What is the best way to determine if text will exceed 1 line? I tried testing by seeing how many 'W' characters could fit, which is 48, but 48 characters in other letters is much much smaller across the screen.

Thanks!!

Dani AI

Generated

As discovered, counting characters is brittle with proportional fonts. @Ardav was right to flag that letter widths vary. Two practical approaches cover most needs: let the browser handle visual truncation with CSS, or measure text precisely on the client when you must produce the actual truncated string.

Use CSS when you only need a visual, single-line ellipsis (no JS or server work). It requires a fixed width container and a block/inline-block element:

.one-line {
  display: inline-block;
  width: 320px;       /* set to your available space */
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

This is the simplest and fastest solution. It is widely supported; see the CSS text-overflow notes for details: text-overflow - MDN.

When the app must return a trimmed string (for feeds, tooltips, or server output), measure rendered width on the client. Using a Canvas 2D context plus a binary-search trim is much faster than removing one character at a time:

function fitToWidth(text, cssFont, maxWidth) {
  var c = document.createElement('canvas');
  var ctx = c.getContext('2d');
  ctx.font = cssFont; // e.g. "normal 16px Arial"
  if (ctx.measureText(text).width <= maxWidth) return text;
  var lo = 0, hi = text.length, best = 0;
  while (lo <= hi) {
    var mid = Math.floor((lo + hi) / 2);
    var candidate = text.slice(0, mid) + '...';
    if (ctx.measureText(candidate).width <= maxWidth) {
      best = mid; lo = mid + 1;
    } else {
      hi = mid - 1;
    }
  }
  return text.slice(0, best) + '...';
}

For server-side precision, use font-metric APIs (GD/imagettfbbox, Pango, FreeType) or render in a headless browser. Always handle multibyte/UTF-8 safely and account for padding, box-sizing and responsive widths. For API details on measuring text in JS, see: CanvasRenderingContext2D.measureText - MDN.

Recommended Answers

All 3 Replies

Member Avatar for Member #120589

Could you use a monospace font (like Courier) which gives each letter the same width. Admittedly, this isn't the nicest looking solution.

You can truncate using:

$display_string = substr($string, 0, 48) . "&hellip;";

You could work out the relative widths of each character and count up to a certain max value. I think this would be overkill, but it's possible.

pseudocode:
start loop
get char at position 'pos'
test width of returned char
add width to total width
check against max allowed width -> IF greater than max
total chars = pos -> break loop
ELSE
increment 'pos'
END IF
end loop

Thanks for your response Ardav! I was hoping maybe there was a better approach out there than counting characters, but possibly not... I have it working with the Character Count, but I'm worried it's not the most efficient way of going about it

Member Avatar for Member #120589

Thanks for your response Ardav! I was hoping maybe there was a better approach out there than counting characters, but possibly not... I have it working with the Character Count, but I'm worried it's not the most efficient way of going about it

You're probably right. But I can't think of another way because as you say 'normal' fonts have different widths for different characters. The only other suggestion would be to do as you've done - find the widest character - find the max no. of those characters and use that total as your basis for truncation. However, it's not likely that you would have a complete line of max width characters - so you could probably get away with a couple more characters on top of this.
Perhaps using styling/css would make the lines look more uniform:

.one_line_text{
  text-align:justify;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.