JSFiddle - React, Tailwind, and code Playground
by Paulpro
HTML
<div id="thediv">This is my text inside a div and I want the overflow of the text to be cut</div>
CSS
#thediv{
width: 302px;
height: 20px;
overflow: hidden;
white-space: nowrap;
}
JavaScript
function count_visible(el){
var padding, em, numc;
var text = el.childNodes[0].data;
var max = el.clientWidth;
var tmp = document.createElement('span');
var node = document.createTextNode();
tmp.appendChild(node);
document.body.appendChild(tmp);
if(getComputedStyle)
tmp.style.cssText = getComputedStyle(el, null).cssText;
else if(el.currentStyle)
tmp.style.cssText = el.currentStyle.cssText;
tmp.style.position = 'absolute';
tmp.style.overflow = 'visible';
tmp.style.width = 'auto';
// Estimate number of characters that can fit.
padding = tmp.style.padding;
tmp.style.padding = '0';
tmp.innerHTML = 'M';
el.parentNode.appendChild(tmp);
em = tmp.clientWidth;
tmp.style.padding = padding;
numc = Math.floor(max/em);
var width = tmp.clientWidth;
// Add characters until we reach overflow width
while(width < max && numc <= text.length){
node.data = text.substring(0, ++numc);
width = tmp.clientWidth;
}
// Remove temporary div
document.body.removeChild(tmp);
// If we passed overflow width subtract one character
return width > max ? numc - 1 : numc;
}