CSS Crop String in The Middle

CSS crop string in the middle

Here is a clean CSS solution using the data-* attribute and two ::after pseudo-elements. I also added an optional hover and show all text (the #fileName::after pseudo element needs to be removed when the full text is shown).

Example 1

#fileName {
position: relative;
width: 100px;
}

#fileName p {
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
}

#fileName:after {
content: attr(data-filetype);
position: absolute;
left: 100%;
top: 0;
}

/*Show on hover*/

#fileName:hover {
width: auto
}

#fileName:hover:after {
display: none;
}
<div id="fileName" data-filetype="txt">
<p>This is the big name of my file.txt</p>
</div>

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>

Is there a way to truncate a string in the middle using CSS or JS?

With css, you can easily use ellipsis, but only at the end of the text.

However, there is a jQuery plugin called dotdotdot, which can do this.

Here's it's page: DotDotDot

One of their demo examples shows, how a long URL can be turned into

www.website.com/that/should/... /file.html


I spent some time trying to get this working properly, and it's still not quite perfect, but works pretty well.

// @param element    obtained with $("selector")
// @param spacer ' ' for text, or '/' for links.
// @param position number of words to leave at end
function doEllipsis(element, spacer, position) {
$(element).data('ell-orig', $(element).html());
$(element).data('ell-spacer', spacer);
$(element).data('ell-pos', position);

var pieces = $(element).html().split(spacer);
if (pieces.length > 1) {

var building = "";

var i = 0;

// for "position" to mean "fraction where to wrap" (eg. 0.6), use this:
// for (; i < pieces.length*position; i++) {

for (; i < pieces.length-position; i++) {
building += pieces[i] + spacer;
}

building += '<span class="ell">';

for (; i < pieces.length; i++) {
building += pieces[i] + spacer;
}

building += '</span>';

$(element).html(building);

$(element).dotdotdot({
after: 'span.ell',
wrap: 'letter'
});
}
}

// use to redraw after the size changes etc.
function updateEllipsis(element) {
var orig = $(element).data('ell-orig');
var spacer = $(element).data('ell-spacer');
var pos = $(element).data('ell-pos');

$(element).trigger("destroy");
$(element).empty();

$(element).html(orig);

doEllipsis(element, spacer, pos);
}

Here's a fiddle of this example (it uses a copy hosted on my dropbox, so it's quite sure that it won't work forever).

It is responsive (to some extent, anyway), and puts the ellipsis exactly where you tell it to.

How should I truncate dynamic string in the middle using JS or CSS?

Use String#replace method with the following regex

((?:[^>]+>){4}).+((?:>[^>]+){4})

Regex explanation here.

Regular expression visualization

$('.selected-option').text(function(i, v) {  return v.replace(/((?:[^>]+>){4}).+((?:>[^>]+){4})/, '$1 ... $2')});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div class="selected-option">Test > run > test > run > test > run > test > run > test > run > test > run > test > run > run > test > run</div>

Text overflow ellipsis the dots should be center of the text

This will not done by using pure CSS, So i found the solution with the help of jQuery.

<div id="wrapper">
<div class="example">
<h1>How to display Text-Overflow:ellipsis dots in center of the text</h1>
<p><strong>Truncate text using jQuery</strong></p>
<div class="r">
<div class="box after pathname" id="dot5">
<div class="pathname">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vitae pretium mauris. Ut tincidunt arcu diam, in congue elit efficitur id. Nunc maximus diam et tellus tincidunt, vitae placerat lacus ullamcorper.</div>
</div>
</div>
</div>
</div>

Css:

div.r {
width: 275px;
background-color:red;
}

div.box {
border: 1px solid #ccc;
height: 40px;
padding: 15px 20px 10px 20px;
}

.pathname {
height: 25px;
color:#fff;
font-size:18px;
}

Javascript:

$(function() {
$('#dot5 .pathname').each(function() {
var path = $(this).html().split(' ');
if (path.length === 0) {
return;
}

var name = path.pop();
$(this).html(path.join( ' ' ) + '<span class="filename">' + name + '</span>');
$(this).dotdotdot({
after: '.filename',
wrap: 'letter'
});
});
});

Demo Here

CSS crop string in the middle

Here is a clean CSS solution using the data-* attribute and two ::after pseudo-elements. I also added an optional hover and show all text (the #fileName::after pseudo element needs to be removed when the full text is shown).

Example 1

#fileName {
position: relative;
width: 100px;
}

#fileName p {
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
}

#fileName:after {
content: attr(data-filetype);
position: absolute;
left: 100%;
top: 0;
}

/*Show on hover*/

#fileName:hover {
width: auto
}

#fileName:hover:after {
display: none;
}
<div id="fileName" data-filetype="txt">
<p>This is the big name of my file.txt</p>
</div>

I need an overflow to truncate from the left, with ellipses

Try to use this trick:

.ellipsis {
overflow: hidden;
width: 60px;
direction: rtl;
margin-left: 15px;
white-space: nowrap;
}

.ellipsis:after {
position: absolute;
left: 0px;
content: "...";
}
<p class="ellipsis">ert3452654546</p>

Truncate text in the middle of a series of divs

Interesting problem - I can't see a reliable CSS-only solution unfortunately. That is, unless the HTML structure can be edited, and even then there will be some hardcoding, I don't believe there is a reliable CSS-only solution.

However, here are 3 potential solutions:

  1. A simple JavaScript utility function
  2. A functional (stateless) React component
  3. A stateful React component

1. A JavaScript Function

In the example below I've created a function truncateBreadcrumbs() which accepts 3 parameters:

  • selector - a CSS selector matching the elements you want to truncate
  • separator - the character used to separate the elements
  • segments - the number of segments you want to truncate the string to

It can be used like:

truncateBreadcrumbs(".js-truncate", "/", 4);

which would find all elements with a class of .js-truncate and truncate the contents to 4 elements, with the ... separator in the middle, like:

Corvid / Games / ... / Night Elf / Malfurion

Odd-numbers of segments can also be used, for example 5 would generate:

Corvid / Games / World of Warcraft / ... / Night Elf / Malfurion

If the segment argument is equal to or greater than the number of elements, no truncation occurs.

And here's the full working example:

function truncateBreadcrumbs(selector, separator, segments) {  const els = Array.from(document.querySelectorAll(selector));
els.forEach(el => { const split = Math.ceil(segments / 2); const elContent = el.innerHTML.split(separator);
if (elContent.length <= segments) { return; }
el.innerHTML = [].concat( elContent.slice(0, split), ["..."], elContent.slice(-(segments-split)) ).join(` ${separator} `); });}
truncateBreadcrumbs(".js-truncate--2", "/", 2);truncateBreadcrumbs(".js-truncate--4", "/", 4);truncateBreadcrumbs(".js-truncate--5", "/", 5);
<div class="js-truncate--2">Corvid / Games / World of Warcraft / Assets / Character Models / Alliance / Night Elf / Malfurion</div>
<div class="js-truncate--4">Corvid / Games / World of Warcraft / Assets / Character Models / Alliance / Night Elf / Malfurion</div>
<div class="js-truncate--5">Corvid / Games / World of Warcraft / Assets / Character Models / Alliance / Night Elf / Malfurion</div>
<div class="js-truncate--4">Corvid / Games / Night Elf / Malfurion</div>


Related Topics



Leave a reply



Submit