Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert ellipsis (...) into HTML tag if content too wide

I have a webpage with an elastic layout that changes its width if the browser window is resized.

In this layout there are headlines (h2) that will have a variable length (actually being headlines from blogposts that I don't have control over). Currently - if they are wider than the window - they are broken into two lines.

Is there an elegant, tested (cross-browser) solution - for example with jQuery - that shortens the innerHTML of that headline tag and adds "..." if the text would be too wide to fit into one line at the current screen/container width?

like image 843
BlaM Avatar asked Feb 11 '09 13:02

BlaM


People also ask

How do you insert an ellipsis in HTML?

To add an ellipsis in the HTML <span> element having the CSS overflow property set to “hidden”, you need to add the text-overflow property. Use its “ellipsis” value, which will add dots at the end of the content within the <span>.

How do I add an ellipsis to a text-overflow?

To clip at the transition between characters you can specify text-overflow as an empty string, if that is supported in your target browsers: text-overflow: ''; . This keyword value will display an ellipsis ( '…' , U+2026 HORIZONTAL ELLIPSIS ) to represent clipped text.

What is overflow ellipsis?

The text-overflow property specifies how overflowed content that is not displayed should be signaled to the user. It can be clipped, display an ellipsis (...), or display a custom string.

Why text-overflow ellipsis is not working?

text-overflow: ellipsis only works when the following is true: The element's width must be constrained in px (pixels) – it doesn't work with values specified using % (percent.) The element must have following properties set: overflow: hidden and white-space: nowrap.


1 Answers

The following CSS only solution for truncating text on a single line works with all browers listed at http://www.caniuse.com as of writing with the exception of Firefox 6.0. Note that JavaScript is totally unnecessary unless you need to support wrapping multiline text or earlier versions of Firefox.

.ellipsis {     white-space: nowrap;     overflow: hidden;     text-overflow: ellipsis;     -o-text-overflow: ellipsis; } 

If you need support for earlier versions of Firefox check out my answer on this other question.

like image 191
Simon Lieschke Avatar answered Sep 23 '22 00:09

Simon Lieschke