Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncate string based on pixel width

I'm trying to make a string fits in a determined area (td) without breaking line. The problem is: It needs to ...

  • Fit while resizing
  • Fit in N kinds of resolution
  • Add ... at the end when needed (and don't when not needed)
  • Accept the change of font-size, font-weight, and font-family

Based on the answers on Novon's question, I made the following code:

CSS (// Just adding some styles to break the line)

.truncated { display:inline-block; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }

jQuery (// Find all td that contains a .truncated element. Getting the real width (by removing the content and adding it again) of the td. Applying, if needed, minWidth on the td)

jQuery('.truncated').closest('td').each(function() {
    var text = jQuery(this).text();
    var widthOriginal = jQuery(this).width();
    var widthEmpty = jQuery(this).text('').width();
    jQuery(this).text(text);
    if(widthOriginal >= widthEmpty){
        var width = (parseInt(widthEmpty) - 10) + 'px';
        jQuery(this).css('maxWidth', width);
        jQuery(this).text(text + '...');
    }
});

the result (as expected from the above code) is:

result

but it should be:

how it should be


I was thinking, maybe try to find the first line of the string and remove the rest but didn't find a way to do that (and it's a lot of "workaround" for my taste). Is there a better way to do that?

like image 972
Michel Ayres Avatar asked Sep 24 '14 14:09

Michel Ayres


3 Answers

Single line text truncation can be easily achieved using css text-overflow property, which is supported by all major browsers, including IE since version 6.

The thing is that text-overflow alone doesn't do much. It only defines what will happen when there is text overflowing the container. So in order to see results, we first need to make the text overflow, by forcing it to a single line. It is also important to set the overflow property of the container:

.truncated {
    display: block;
    white-space: nowrap; /* forces text to single line */
    overflow: hidden;
    text-overflow: ellipsis;
}

jsFiddle example: https://jsfiddle.net/x95a4913/

text-overflow documentation: https://developer.mozilla.org/en-US/docs/Web/CSS/text-overflow

like image 79
Hugo Silva Avatar answered Nov 10 '22 19:11

Hugo Silva


You can do it with pure CSS, see this link for reference:

line clampin

Add those to your css:

.truncated {
  display: -webkit-box;
  -webkit-line-clamp: 1; // amount of line you want
  -webkit-box-orient: vertical;  
}

Or you can try clamp.js

https://github.com/josephschmitt/Clamp.js

like image 24
Caio Kawasaki Avatar answered Nov 10 '22 20:11

Caio Kawasaki


text-overflow: ellipsis

seems a pure CSS solution http://www.w3schools.com/cssref/css3_pr_text-overflow.asp

like image 7
Francesco Avatar answered Nov 10 '22 20:11

Francesco