Tech Talk

Permanent link to Autofit text in a web browser Autofit text in a web browser

Wednesday, April 2, 2008
If you've ever tried to make text fit vertically on a web page, you know you're in for frustrations. Just getting stuff to fill up 100% of the page exactly is a royal pain! You long for something like Powerpoint's "autofit" features, but CSS gives no such property. However, when a slideshow or kiosk-mode application is at stake, fitting text is critical.

I tried for a while to estimate the size on the server size and adjust the font size based on how much text there was, but that didn't work too well with extra HTML formatting, breaks, lists, images, etc.

So, I've come up with a Javascript version that runs when on page load, and shrinks the text in a div until the div's height is less than that the browser window:

function fitText(divID){
    divShrink = document.getElementById(divID);
    intDivH = divShrink.clientHeight;
    intWinH = window.innerHeight != null? window.innerHeight: document.body != null? document.body.clientHeight:null;
    while (intDivH>intWinH&&s>0){
        intDivH = divShrink.clientHeight;


LaRocque Family