Ellipsis in the middle of a text (Mac style)
In the HTML, put the full value in a custom data-* attribute like
<span data-original="your string here"></span>
Then assign load
and resize
event listeners to a JavaScript function which will read the original data attribute and place it in the innerHTML
of your span tag. Here is an example of the ellipsis function:
function start_and_end(str) {
if (str.length > 35) {
return str.substr(0, 20) + '...' + str.substr(str.length-10, str.length);
}
return str;
}
Adjust the values, or if possible, make them dynamic, if necessary for different objects. If you have users from different browsers, you can steal a reference width from a text by the same font and size elsewhere in your dom. Then interpolate to an appropriate amount of characters to use.
A tip is also to have an abbr-tag on the ... or who message to make the user be able to get a tooltip with the full string.
<abbr title="simple tool tip">something</abbr>
I'd like to propose mine example of solving this problem.
The main idea is to split text in two even parts (or first is bigger, if the length is odd) one of which has ellipsis in the end and another aligned right with text-overflow: clip
.
So all you need to do with js, if you want to make it automatic/universal - is to split string and set attributes.
It has some disadvantages, though.
- No nice wrapping by words, or even letters (
text-overflow: ''
works only in FF at the moment) - If the split happens between words - space should be in the first part. Otherwise, it will be collapsed.
- End of the string should not have any exclamation marks, due to
direction: rtl
- they will be moved to the left of the string. I think, it is possible to fix this with putting right part of the word in the tag and exclamation mark in the::after
pseudo-element. But I haven't yet made it properly working.
But, with all of these, it looks really cool to me, especially when you dragging the border of the browser, which you can do on the jsfiddle page easily: https://jsfiddle.net/extempl/93ymy3oL/. Or just run the snippet with fixed max-width below.
Gif under the spoiler:
body {
max-width: 400px;
}
span::before, span::after {
display: inline-block;
max-width: 50%;
overflow: hidden;
white-space: pre;
}
span::before {
content: attr(data-content-start);
text-overflow: ellipsis;
}
span::after {
content: attr(data-content-end);
text-overflow: '';
direction: rtl;
}
<span data-content-start="Look deep into nature, and then you "
data-content-end= "will understand everything better"></span>
<br>
<span data-content-start="https://www.google.com.ua/images/branding/g"
data-content-end= "ooglelogo/2x/googlelogo_color_272x92dp.png"></span>