Wednesday, January 6, 2016

HTML Fit Content to Available Space - Dynamic Font Size

Hello,

Recently in one of my project we have to fit content to available screen height. Basically it was cross platform mobile application built in HTML 5 and JavaScript. On screen there was a card with content. Card height and width as set to screen height and width. Now the problem was content can big or small and there should not be scrollbar. So what I did is I reduced the size of font till the content fits available width and height. This I did in JavaScript. So here in blog I am going to explain how to do this.

First of all add onload method to your body tag.

<body onload="resizeFontSizeInit()">

   <div id="contentContainer" style="width:100%;height:100%;overflow:hidden;">
       <div id="content">
        Dynamic Content Here
       </div>
   </div>

</body>

Now add following function to JavaScript

function resizeFontSizeInit(){
   resizeFont(0.1);
}

function resizeFont(emSize){
      //first get the screen height
      var screenHeight = document.documentElement.clientHeight;
   
      //Now set the font size to content div
      var contentDiv = document.getElementById('content');
      contentDiv.style.fontSize = String(emSize)+"em";

      //Now check the height of screen to height of content div
      var contentHeight = contentDiv.clientHeight;

      //Check if content height is less than screen height.
      if(contentHeight < screenHeight){
           //Increase font size and call the same function recursively.
           emSize = emSize + 0.1;
           resizeFont(emSize);
      }else{
           //content height is greater than screen size so time to stop recursion.
          //set fontsize to previous size.
          revertFontSizeToPreviousSize(emSize);
      }
}

function revertFontSizeToPreviousSize(emSize){
      emSize = emSize - 0.1;
      var contentDiv = document.getElementById('content');
      contentDiv.style.fontSize = String(emSize)+"em";
}

So basically we start with 0.1 em font size and keep increasing it till the content height is greater than screen height. As soon as it's bigger we have to stop and reset it to previous size. This way no matter what your content is, it will fit to screen without scroll bar.

No comments:

Post a Comment