The width property sets or returns the width an element.
The width property has effect only on block-level elements or on elements with absolute or fixed position. The overflowing content can be manipulated with the overflow property.
Use the height property to set or return the height of an element.
Syntax and Usage
Return the width property: object.style.width Set the width property: object.style.width = "auto|length|%|initial|inherit"
Property Values
Value | Description |
---|---|
auto | The browser sets the width. This is default |
length | Defines the width in length units |
% | Defines the width in % of the parent element |
initial | Sets this property to its default value. |
inherit | Inherits this property from its parent element. |
Return Value: A String, representing the width of an element
Example(1)
<button class="btn btn-info" type="button" id="Btn" onclick="width_function()">Change the width of this button</button> <script> function width_function() { document.getElementById("Btn").style.width = "300px"; } </script>
In above example when you click button it will maximum the button width.
<style> #DIV { width: 100px; height: 100px; background-color: coral; color: white; } </style> <button onclick="div_function()">Click it</button> <div id="DIV"> <h2>myDIV</h2> </div> <script> function div_function() { document.getElementById("DIV").style.width = "500px"; } </script>
In above example when you click button it will change the width of the DIV element.
<img id="Img" src="../image/demo2.jpg" width="100" height="132"> <br> <button type="button" onclick="image_function()">Change height and width of image</button> <script> function image_function() { document.getElementById("Img").style.height = "300px"; document.getElementById("Img").style.width = "300px"; } </script>
<!DOCTYPE html> <html> <head> <title>Use CSS Style Width Properties With JavaScript</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> </head> <style> h1 { color: red; } #DIV { width: 100px; height: 100px; background-color: coral; color: white; } </style> <body> <div class="container"> <br> <div class="text-center"> <h1>Use CSS Style Width Properties With JavaScript</h1> </div> <br> <div class="col-md-6"> <img id="Img" src="../image/demo2.jpg" width="100" height="132"> <br> <br> <button class="btn btn-info" type="button" onclick="image_function()">Change height and width of image</button> </div> <div class="col-md-6"> <div id="DIV"> <h2>myDIV</h2> </div> <br> <button onclick="div_function()">CLick it</button> </div> </body> </html> <script> function image_function() { document.getElementById("Img").style.height = "300px"; document.getElementById("Img").style.width = "300px"; } function div_function() { document.getElementById("DIV").style.width = "500px"; } </script>