DynamicFontSize


Responsive web design is the practice of building a website suitable to work on every device and every screen size, no matter how large or small, mobile or desktop. There are many ways to achieve this effect. But in this post we only focus on font-size and headlines.

CSS text does not scale automatically. To keep the text in size we need javascript support. First we measure the size of the parent element then we set the font-size accordingly.

 

get & set size

Normally you would call the changeFontSize() function in the onload() function. And get the scale factor from the viewport size.

In this case we get the scale factor from the text parent object. Since we don’t change the viewport size.

function changeFontSize()
{
    //GET THE TEXT CONTAINER
    var wrapper = document.getElementById("wrapper");

    //ADD ELEMENTS THAT SCALE WHIT PARENT
    var children = [wrapper.getElementsByTagName('h1'),wrapper.getElementsByTagName('h2'),wrapper.getElementsByTagName('h3')];

    //SET THE SCALE FACTOR
    factor = wrapper.clientWidth / startWidth;

    //LOOP TROUGH EVERY ELEMENT 
    for (var i=0;i<children.length;i++)
    {   
        for (var j=0;j<children[i].length;j++)
        { 
            //SET THE BASIC CSS VALUE
            children[i][j].style.fontSize = null;
            //GET ORIGINAL FONT-SIZE OF THE ELEMENT
            fontSize = parseInt( window.getComputedStyle( children[i][j], null ).getPropertyValue( 'font-size' ).replace('px','') ,10);

            //GET THE NEW FONT-SIZE
            fontSize = fontSize * factor;
            fontSize = fontSize.toFixed(2);

            //APPLY FONT-SIZE
            children[i][j].style.fontSize = fontSize +"px";

        };
    };
}

 

conclusion

This is a great technic to make your design more responsive. Easy to implement and no additional libraries needed.