I'm trying to make a string fits in a determined area (td
) without breaking line. The problem is: It needs to ...
N
kinds of resolution...
at the end when needed (and don't when not needed)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:
but 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?
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
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
text-overflow: ellipsis
seems a pure CSS solution http://www.w3schools.com/cssref/css3_pr_text-overflow.asp
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With