JSFiddle - React, Tailwind, and code Playground
HTML
<p>Put your text here :</p>
<textarea id="src"></textarea>
<p>... and see the result here :</p>
<div id="container">
<div id="text"></div>
</div>
CSS
body, html {height:100%; width:100%; overflow:hidden}
#src{width:90%; height:100px}
#container{
width:50%; height:30%;
background:#DDD;
margin:2em;
padding:1em;
display:-webkit-box; -webkit-box-orient:vertical; -webkit-box-pack: center; -webkit-box-align:center;
display:-moz-box; -moz-box-orient:vertical; -moz-box-pack: center; -moz-box-align: center;
display:-ms-flexbox; -ms-flex-direction: column; -ms-flex-pack: center; -ms-flex-align:center;
display:-webkit-flex; -webkit-flex-direction:column; -webkit-justify-content: center; -webkit-align-items:center;
display:flex; flex-direction:column; justify-content: center; align-items:center;
}
#text {
/* do not set any padding or margin for this element */
max-width:100%; max-height:100%;
font-size:1em;
overflow:hidden;
/*text-overflow: initial;*/
-ms-word-break: break-all;
word-break: break-all;
-webkit-hyphens: auto;
-moz-hyphens: auto;
hyphens: auto;
text-align:center;
}
JavaScript
var maxFontSize=68; // I think we cannot have bigger than that.
var minFontSize=12;
$('#text').on({
// setting an event to resize text
resize:function(e){
// if no text => return false;
if (!$(this).html().trim()) return;
// if already running => return false;
if (this.running) return;
this.running = true;
// get max-height = height of the parent element
var h = $(this).parent().height();
// clone the text element and apply some css
var clone = $(this).clone()
.removeAttr('id')
.css({'font-size':0,
'width':$(this).width(),
'opacity':0,
'position':'fixed',
'left':-1000})
.appendTo($('body'));
// Set the max font size for the clone to fit the max height;
var fontSize = minFontSize;
do {
$(this).css('font-size', fontSize+'px');
fontSize=fontSize+1;
clone.css('font-size', fontSize+'px');
} while (h > clone.height() && maxFontSize > fontSize) ;
// Set the '...' if still bigger
//start by setting back the good size to the clone.
fontSize=fontSize-1;
clone.css('font-size', fontSize+'px');
// while max-height still bigger than clone height
if (h < clone.height() && minFontSize == fontSize) {
var content = clone.html();
// try to remove the last words, one by one.
while (h < clone.height()) {
content = content.replace(/(\s[^\s]*)$/g,'...');
clone.html(content);
}
// then replace the #text content
$(this).html(clone.html());
}
// then remove the...