Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Have font size change according to size of div

I have a resisable div with text inside. I want the text to scale as the div changes size.

Specifically, I want the text to have the largest possible font size that will make it fit inside the div.

like image 976
Randomblue Avatar asked Oct 09 '22 15:10

Randomblue


2 Answers

Use FitText http://fittextjs.com/

like image 159
Idered Avatar answered Oct 13 '22 10:10

Idered


I use this plugin that I made based on fitText.js, because fitText doesn't fit my needs, due to I don't know the length of the strings to resize, so the fix resize parameter of fitText don't work in all cases.

$.fn.adjustTextSize = function (set_max_size, min_size) {
    min_size = min_size || 12; // if no value then set a default one
    var string, width, line, initFontSize, returnFontSize, ratio;

    return this.each(function() {
        // Store the object
        var $this = $(this);

        var resizer = function () {
            string = $this;
            string.html('<span style="white-space: nowrap;">' + string.html() + '</span>');

            width = string.width();
            line = $(string.children('span'));
            initFontSize = parseInt(string.css('font-size'));
            ratio = width/line.width();

            returnFontSize = initFontSize*ratio;

            if (set_max_size && returnFontSize > initFontSize) {
                returnFontSize = initFontSize;
            }

            if (min_size && returnFontSize < min_size) {
                returnFontSize = min_size;
            }

            string.css('font-size',returnFontSize);
            while (line.width() >= width) {
                if (min_size && returnFontSize <= min_size) {
                    string.html(line.html());
                    return false;
                }
                string.css('font-size', --returnFontSize);
            }
            string.html(line.html());
        }

        // Call once to set.
        resizer();

        // Call on resize. Opera debounces their resize by default.
        $(window).on('resize orientationchange', resizer);
    });
};
$('.js-adjust-text').adjustTextSize(false, 12);
$('.js-adjust-text-limit').adjustTextSize(true, 30);

This plugin get two parameters:

  • set_max_size: boolean to limit maximum font size to its defined size in CSS
  • min_size: Integer number to limit minimum font size.

I hope it works for your case.

like image 23
Jaime Fernandez Avatar answered Oct 13 '22 11:10

Jaime Fernandez