JSFiddle - React, Tailwind, and code Playground

by Ankit Patidar

HTML

<div class="jtextfill"><h1>foohgjgh</h1></div>

CSS

.jtextfill {
    width:100px;
    background:yellow;
    height:100px;
}

h1 {
    display:inline;
    border:1px solid red;
}

JavaScript

(function($) {
    /**
    * Resizes an inner element's font so that the inner element completely fills the outer element.
    * @author Russ Painter [email protected]
    * @version 0.1
    * @param {Object} Options which are maxFontPixels (default=40), innerTag (default='span')
    * @return All outer elements processed
    * @example <div class='mybigdiv filltext'><span>My Text To Resize</span></div>
    */
    $.fn.textfill = function(options) {
        var defaults = {
            maxFontPixels: 40,
            innerTag: 'span'
        };
        var Opts = jQuery.extend(defaults, options);
        return this.each(function() {
            var fontSize = Opts.maxFontPixels;
            var ourText = $(Opts.innerTag + ':visible:first', this);
            var maxHeight = $(this).height();
            var maxWidth = $(this).width();
            var textHeight;
            var textWidth;
            do {
                ourText.css('font-size', fontSize);
                textHeight = ourText.height();
                textWidth = ourText.width();
                fontSize = fontSize - 1;
            } while ((textHeight > maxHeight || textWidth > maxWidth) && fontSize > 3);
        });
    };
})(jQuery);

$(document).ready(function() {
    $('.jtextfill').textfill({ maxFontPixels: 200, innerTag: 'h1' });
});