My Technical Notes

Thursday, 11 December 2014

Automatic Resizing of Font to fit in Container

In the following snippet, `.wizard-header` is the target of the automatic resizing. `.page-content` is the container that we want to constrain it to. `16` is the start font. `5` is the minimum font. (both in px).


(function () {
    // resize is called multiple times
    function resizer() {
        console.log('resizer');
        var narrow = Modernizr.mq("screen and (max-width: 750px)");

        var $wizHeader = $('.wizard-header');

        // (don't need to set the white-space to 'nowrap' because this is handled by the CSS)
        // reset the font-size prior to changing it.
        $wizHeader.css('font-size', '');
        if (narrow) {
            if ($wizHeader.width() >= $('.page-content').width()) {
                var fontSize = 16;
                while ($wizHeader.width() >= $('.page-content').width() && fontSize >= 5) {
                    $wizHeader.css('font-size', fontSize + 'px');
                    fontSize--;
                }
            }
        }
    }
    
    resizer();

    $(window).on('resize orientationchange', resizer);
})();

No comments: