JSFiddle - React, Tailwind, and code Playground
HTML
<div class="textfill">This is just a simple text</div>
<div class="textfill"><span class="c1">text1</span>main text<span class="c2">text2</span></div>
CSS
.textfill {
width: 530px;
height: 240px;
font-size: 9px;
text-align: center;
border: 1px solid #ccc;
margin: 10px;
}
.c1 {
font-family: Arial;
font-size: 12px;
}
.c2 {
font-family: Courier New;
font-size: 20px;
color: red;
}
JavaScript
(function($) {
$.fn.textfill = function(options) {
return this.each(function() {
var text = $(this).html();
var oldFontSize = parseInt($(this).css("font-size"));
var contentFontSizes = [];
$(this).find('*').each(function(i, e){
contentFontSizes[i] = parseInt($(this).css("font-size"));
});
$(this).html('');
var container = $('<span />').html(text).appendTo($(this));
var min = 1, max = 200, fontSize;
do {
fontSize = (max + min) / 2;
container.css('fontSize', fontSize);
container.find('*').each(function(i, e){
$(this).css("font-size", fontSize);
});
var multiplier = $(this).height()/container.height();
if (multiplier == 1) { min = max = fontSize}
if (multiplier > 1) { min = fontSize}
if (multiplier < 1) { max = fontSize}
} while ((max - min) > 1);
fontSize = min;
coef = fontSize / oldFontSize;
if ($(this).width() < container.width()) {
min = 1;
do {
fontSize = (max + min) / 2;
container.css('fontSize', fontSize);
container.find('*').each(function(i, e){
$(this).css("font-size", fontSize);
});
var multiplier = $(this).width()/container.width();
if (multiplier == 1) { min = max = fontSize}
if (multiplier > 1) { min = fontSize}
if (multiplier < 1) { max = fontSize}
} while ((max - min) > 1);
fontSize = min;
coef = fontSize / oldFontSize;
}
container.remove();
$(this).html(text);
var minFontSize = options.minFontPixels;
var maxFontSize = options.maxFontPixels;
var newFontSize = minFontSize && (minFontSize > fontSize) ?
minFontSize :
...