PHLAK PHLAK - 7 months ago 29
Javascript Question

Is it possible to dynamically scale text size based on browser width?

Here is the project this is for: As you can see, right now the text size is just set to a static size. I'd like the text to always be ~90% of the width of the window but to also scale the vertical size accordingly. Is there a relatively easy way of doing this?


Hell yeah!

Set your <body> font size when the window is resized with a little javascript. (I've used jQuery for convenience here:

$( document ).ready( function() {
            var $body = $('body'); //Cache this for performance

            var setBodyScale = function() {
                var scaleSource = $body.width(),
                    scaleFactor = 0.35,                     
                    maxScale = 600,
                    minScale = 30; //Tweak these values to taste

                var fontSize = scaleSource * scaleFactor; //Multiply the width of the body by the scaling factor:

                if (fontSize > maxScale) fontSize = maxScale;
                if (fontSize < minScale) fontSize = minScale; //Enforce the minimum and maximums

                $('body').css('font-size', fontSize + '%');


            //Fire it when the page first loads:

Because your font size is set in em's (perfect) adjusting the percentage font-size of the body element acts as a universal 'text zoom'. This will scale any text set in em's - if you want to be more specific, you could set the percentage font-size on a <div> that surrounds just the elements you want to scale.

Here's a quick example: