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?
Here is a nice widget/plugin library which has ellipsis built in: http://www.codeitbetter.co.uk/widgets/ellipsis/ All you need to do it reference the library and call the following:
There's a solution for multi-line text with pure css. It's called
line-clamp
, but it only works in webkit browsers. There is however a way to mimic this in all modern browsers (everything more recent than IE8.) Also, it will only work on solid backgrounds because you need a background-image to hide the last words of the last line. Here's how it goes:Given this html:
Here's the CSS:
ellipsis_bg.png being an image of the same color of your background, that would be about 100px wide and have the same height as your line-height.
It's not very pretty, as your text may be cut of in the middle of a letter, but it may be useful in some cases.
Reference: http://www.css-101.org/articles/line-clamp/line-clamp_for_non_webkit-based_browsers.php
There is a simple jQuery solution by Devon Govett:
https://gist.github.com/digulla/5796047
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.
If you need support for earlier versions of Firefox check out my answer on this other question.
This is similar to Alex's but does it in log time instead of linear, and takes a maxHeight parameter.
I built this code using a number of other posts, with the following enhancements:
display: block
to the style, so spans workCSS:
jquery.ellipsis.js