JSFiddle - React, Tailwind, and code Playground
HTML
<div>
<p>123456789012345678901234567890</p>
<p>12345678901234567890</p>
<p>1234567890</p>
</div>
CSS
div {
width: 100%;
}
p {
border: 1px dashed #000;
position: relative;
display: block;
width: 50%;
}
p:before {
content:attr(data-shortened);
color: #000;
display: block;
position: absolute;
top: 0;
left: 0;
width: 100%;
}
JavaScript
function shortenContent(content, chars) {
/* chars here determines how many characters
* we want on either side of the elipsis. */
var chars = chars || 3; // Default is 3
if (!content && !content.length)
return;
/* Loop through each content element and
* shorten where necessary. */
for (i = 0; i < content.length; i++) {
var el = content[i],
elementWidth = el.offsetWidth,
textWidth = el.scrollWidth;
/* If our element's width is less than
* its content's width, we need to shorten. */
if (elementWidth < textWidth) {
var text = el.innerText;
/* Set the data attribute for the CSS to use. */
el.setAttribute(
'data-shortened', text.slice(0, chars) + '...' + text.slice(-chars)
);
el.style.color = 'rgba(0, 0, 0, 0)';
}
/* Otherwise, ensure non-shortened text is visible. */
else {
el.setAttribute('data-shortened', '');
el.style.color = null;
}
}
}
// Get the content we wish to shorten
var content = document.querySelectorAll('div p');
/* Trigger the function initially. */
shortenContent(content);
/* Fire the shorten function when the window resizes. */
window.onresize = function(event) {
shortenContent(content);
};