JSFiddle - React, Tailwind, and code Playground
HTML
<div class='jtextfill' style='width:200px;height:100px;'>
<span>Now is a good time to party!</span>
</div>
<div class='jtextfill' style='width:200px;height:100px;'>
<span>Now is a good time to party!</span>
</div>
<div class='jtextfill' style='width:200px;height:100px;'>
<span>Now is a good time to party!</span>
</div>
<div class='jtextfill' style='width:200px;height:100px;'>
<span>Now is a good time to party!</span>
</div>
<div class='jtextfill' style='width:200px;height:100px;'>
<span>Now is a good time to party!</span>
</div>
<div class='jtextfill' style='width:200px;height:100px;'>
<span>Now is a good time to party!</span>
</div>
<div class='jtextfill' style='width:200px;height:100px;'>
<span>Now is a good time to party!</span>
</div>
<div class='jtextfill' style='width:200px;height:100px;'>
<span>Now is a good time to party!</span>
</div>
<div class='jtextfill' style='width:200px;height:100px;'>
<span>Now is a good time to party!</span>
</div>
<div class='jtextfill' style='width:200px;height:100px;'>
<span>Now is a good time to party!</span>
</div>
<div class='jtextfill' style='width:200px;height:100px;'>
<span>Now is a good time to party!</span>
</div>
<div class='jtextfill' style='width:200px;height:100px;'>
<span>Now is a good time to party!</span>
</div>
<div class='jtextfill' style='width:200px;height:100px;'>
<span>Now is a good time to party!</span>
</div>
<div class='jtextfill' style='width:200px;height:100px;'>
<span>Now is a good time to party!</span>
</div>
<div class='jtextfill' style='width:200px;height:100px;'>
<span>Now is a good time to party!</span>
</div>
<div class='jtextfill' style='width:200px;height:100px;'>
<span>Now is a good time to party!</span>
</div>
<div class='jtextfill' style='width:200px;height:100px;'>
<span>Now is a good time to party!</span>
</div>
<div class='jtextfill' style='width:200px;height:100px;'>
<span>Now is a good time to...
CSS
.jtextfill {
background-color:red;
}
JavaScript
(function($) {
$.fn.textfill = function(options) {
var start = (new Date).getTime(),
setPosition = true,
node = $(this),
fontSize = 3,
ourText = $('span:visible:first', this),
maxHeight = node.height(),
maxWidth = node.width(),
textHeight,
textWidth;
// Take the node out of the flow for faster relayout
if (setPosition) node.css('position', 'absolute');
do {
ourText.css('font-size', fontSize);
textHeight = ourText.height();
textWidth = ourText.width();
fontSize = fontSize + 1;
} while ((textHeight <= maxHeight && textWidth <= maxWidth) && fontSize <= options.maxFontPixels);
ourText.css('font-size', fontSize - 2);
// Remove temporary positioning
node.css('position', '');
console.log('elements:', node.size(), 'setPosition:', setPosition, 'elapsed time:', (new Date).getTime() - start);
return this;
}
})(jQuery);
$(document).ready(function() {
$('.jtextfill').textfill({ maxFontPixels: 200 });
});