The Wayback Machine - https://web.archive.org/web/20240204103925/https://www.geeksforgeeks.org/how-to-set-font-size-based-on-window-size-using-javascript/
Open In App
Related Articles

How to set font size based on window size using JavaScript ?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Given an HTML document and the task is to change the font-size based on the size of the window with the help of JavaScript. 

Approach 1:

  • First convert the document element font sizes to em or % by using a function.
  • Call this function on every resize of the window. It will change the font size based on window size.

Example: This example implements the above approach. 

html




<h1 id="h1" style="color: green">
    GeeksForGeeks
</h1>
  
<p id="GFG_UP" style="font-weight: bold;">
</p>
  
<script>
    var up = document.getElementById('GFG_UP');
    var h1 = document.getElementById('h1');
      
    up.innerHTML = "Resize the window to change"
        + "the font-size based on window-size";
      
    h1.setFont = function (font) {
        var size = this.offsetWidth,
        font_size = size * font;
        this.style.fontSize = font_size + '%';
        return this
    };
      
    h1.setFont(0.50);
      
    window.onresize = function () {
        h1.setFont(0.50);
    }
</script>


Output:

 

Approach 2: Use vw(viewport) unit with the font-size to convert the font-size with respect to the viewport. 

Example: This example implements the viewport approach. 

html




<h1 style="color: green; font-size: 5vw;">
    GeeksForGeeks
</h1>
  
<p id="GFG_UP" style="font-weight: bold;">
</p>
  
<script>
    var up = document.getElementById('GFG_UP');
    up.innerHTML = "Resize the window to change"
        + "the font-size based on window-size";
</script>


Output:

 


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Looking for a place to share your ideas, learn, and connect? Our Community portal is just the spot! Come join us and see what all the buzz is about!


Last Updated : 21 Dec, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads
Complete Tutorials