How to set width and height of an element using jQuery?

To set the width and height of an element using jQuery, use the width() and height() methods in jQuery. These methods allow you to dynamically modify element dimensions with pixel values or other CSS units.

Setting Width of an Element

The width()

Example

You can try to run the following code to learn how to set the width of an element in jQuery ?

<!DOCTYPE html>
<html>
   <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <script>
         $(document).ready(function(){
            $("#button1").click(function(){
               $("div").width(300);
            });
            $("#button2").click(function(){
               $("div").width(400);
            });
         });
      </script>
   </head>
   <body>
      <div style="height:150px;width:200px;border:2px solid gray;background-color:lightblue;"></div><br>
      <button id="button1">Width of div: 300</button>
      <button id="button2">Width of div: 400</button><br>
   </body>
</html>

Setting Height of an Element

The height() method works similarly to width(), accepting numeric values to modify element height dynamically.

Example

You can try to run the following code to learn how to set the height of an element in jQuery ?

<!DOCTYPE html>
<html>
   <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <script>
         $(document).ready(function(){
            $("#button1").click(function(){
               $("div").height(250);
            });
            $("#button2").click(function(){
               $("div").height(350);
            });
         });
      </script>
   </head>
   <body>
      <div style="height:150px;width:400px;border:2px solid gray;background-color:lightblue;"></div><br>
      <button id="button1">Height of div: 250</button>
      <button id="button2">Height of div: 350</button><br>
   </body>
</html>

Conclusion

jQuery's width() and height() methods provide an easy way to dynamically modify element dimensions, making them essential for responsive web design and interactive user interfaces.

Updated on: 2026-03-13T18:49:45+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements