HowTo fit text inside a UIWebView

If, like me, you want to make sure your text will fit inside your UIWebView (without scrolling), you can implement the following javascript:

    <script language='javascript' type="text/javascript">
    function adjustHeight(maxHeight) {
      elem = document.getElementById("sign");
      height = elem.offsetHeight;
      current_size ='px','')/1;
      while ((current_size-- > 10) && (height > maxHeight)){ = current_size + 'px';
        height = elem.offsetHeight;

This script will reduce the size of the div until it fits the required height, but with a minimum font-size of 10px hardcoded.

Now in the html, call the adjustHeight function, passing it the id of the div to adjust:

<body onload="adjustHeight(48)">
  <div id="sign" style="font-size:68px">This is the text that fits</div>

The trick here is that to read the fontSize of a div, the font-size property should be inline. If the font-size is declared in the CSS, you’ll have to use another much more complex method, described in

PS: Instead of reading the font-size from the div, I could have hardcoded its value in the script, and avoided much trouble.

Leave a Reply

Your email address will not be published. Required fields are marked *