CSS overflow detection in JavaScript
Posted
by
ring0
on Stack Overflow
See other posts from Stack Overflow
or by ring0
Published on 2010-12-30T04:49:23Z
Indexed on
2010/12/30
4:54 UTC
Read the original article
Hit count: 274
JavaScript
|css
In order to display a line of text (like in a forum), and end that line with "..." if the text would overflow the line (not truncating using the CSS overflow
property), there are a number of ways. I'm still seeking the best solution. For instance,
Adding in CSS a "..." as a background-image is a possibility, but it would appear all the time, and this is not a good solution.
Some sites just count the characters and if over - say - 100, truncates the string to keep only 100 (or 97) chars and add a "..." at the end. But fonts are usually not proportional, so the result is not pretty. For instance the space - in pixels - taken by
- "AAA" and "iii" is clearly different
"AAA"
and"iii"
via a proportional font have the same width
There is another idea to get the exact size in pixels of the string:
- create in Javascript a DIV
- insert the text in it (via innerHTML for instance)
- measure the width (via .offsetWidth)
which is not implemented yet. However, I wonder if there could be any browser compatibility problem?
Did any one tried this solution? Other recommendations would be welcome.
© Stack Overflow or respective owner