JSFiddle - React, Tailwind, and code Playground
HTML
<div id="container">My text string here.aasasas</div>
CSS
#container {font-size:10px;width:300px;height:100px;border:1px solid red;}
JavaScript
(function($) {
$.textMetrics = function(el) {
var h = 0,
w = 0;
var div = document.createElement('div');
document.body.appendChild(div);
$(div).css({
position: 'absolute',
left: -1000,
top: -1000,
display: 'none'
});
$(div).html($(el).html());
var styles = ['font-size', 'font-style', 'font-weight', 'font-family', 'line-height', 'text-transform', 'letter-spacing'];
$(styles).each(function() {
var s = this.toString();
$(div).css(s, $(el).css(s));
});
h = $(div).outerHeight();
w = $(div).outerWidth();
$(div).remove();
var ret = {
height: h,
width: w
};
return ret;
}
})(jQuery);
//Fit to size function
(function($) {
$.fitToSize = function(el) {
var defaultFontSize = 10;
var textWidth = $.textMetrics(el).width;
var rate = $(el).width() / textWidth;
$(el).css('font-size', rate*defaultFontSize);
}
})(jQuery);
//Done!
$.fitToSize('#container');