Open In App

How to make font-size that expands when we resize the window using jQuery ?

Last Updated : 12 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn how to increase or decrease the font-size of elements in HTML when the window is resized using jQuery. This can be used in situations where the font size has to be responsive according to the width of the browser window.

Approach: We will be using the jQuery css(), width() and resize() methods. As the font size has to be changed according to the resizing of the window, the resize() method can be applied to the window object. Now, a callback function has to be defined within this resize() method. Inside this function, we will select all elements in the HTML document using the $(*) selector. We will then modify the font-size property using the css() method and make the font-size relative to a percentage of the window width in pixels. This function will get repeatedly executed when the window size resizes.

Example: In this example, all the element font sizes are adjusted according to 8% of the window width.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <script src=
    </script>
  
    <!-- Basic inline styling -->
    <style>
        body {
            text-align: center;
        }
  
        h1 {
            color: green;
            font-size: 25px;
        }
  
        p {
            font-weight: bold;
            font-size: 25px;
        }
    </style>
</head>
  
<body>
    <h1>GeeksforGeeks</h1>
  
    <p>
        Notice the scaling in font size
        as the window is resized
    </p>
  
    <script type="text/javascript">
        $(window).resize(function () {
              
            // Calculate the final font size 
            // to be 8% of the window width
            let size = $(window).width() * 0.08;
  
            // Use the css() method to set the
            // font-size to all the elements on
            // the page
            $("*").css("font-size", size + "px");
        });
    </script>
</body>
  
</html>


Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads