17

I have some dynamic text (comes from a database) and I need to fit into a div

My div has a fixed size. However, when the text becomes too long, it breaks into two lines. I would like to put three dots at the end of longer texts to make them fit inside a single line.

For example: My really long text becomes My really lo...

I have committed several attempts, but basically all of them depend on counting characters. That is, whatsoever, not really fortunate, for characters do not have a fixed width. For example, a capital W is much wider than an small i

Therefore, I encounter two main problems with the character-counting approach:

  1. If the text has many narrow characters, it gets cut and appended with ..., even if the text would actually fit on one line afore trimmed.

  2. When the text contains many wide characters, it ends up on two lines even after I cut it to the maximum number of characters and append the dots.

Is there any solution here (JavaScript or CSS) that takes the actual width of the text into consideration, and not the number of characters?

undefined
  • 1,019
  • 12
  • 24
Øyvind Bråthen
  • 59,338
  • 27
  • 124
  • 151

4 Answers4

51

Use these styles:

white-space: nowrap;      /*keep text on one line */
overflow: hidden;         /*prevent text from being shown outside the border */
text-overflow: ellipsis;  /*cut off text with an ellipsis*/
VirtualScooter
  • 1,792
  • 3
  • 18
  • 28
James Coyle
  • 9,922
  • 1
  • 40
  • 48
4

Apart from ellipsis, I would suggest display the whole text on mouse hover using tooltip.

fiddle

Shouvik
  • 11,350
  • 16
  • 58
  • 89
2

I would suggest Trunk8

You can then make any text fit to the size of the div, it trims the text that would cause it to go beyond 1 line (options are available to set amount of lines allowed)

E.g

$('.truncate').trunk8();
Ryan McDonough
  • 9,732
  • 3
  • 55
  • 76
1

You should look at css ellipsis : http://www.w3schools.com/cssref/css3_pr_text-overflow.asp

Kev
  • 5,049
  • 5
  • 32
  • 53