This blog demonstrates the DOM element clientWidth in HTML.
How to Use DOM Element “clientWidth” in HTML?
The “clientWidth” property returns the width of the visible element content, leaving the border, margin, and width of the scrollbar if it is used. It helps in creating the layout and the positioning of HTML elements and tells whether the element fits or not within the specified space.
Let us walk through an example for a better explanation:
Example: The “clientWidth” Property
In this example, the width of an HTML element is going to retrieve using the “clientWidth” property:
An explanation of the above code snippet is described below:
- First, create an “<h3>” tag that holds some dummy data. Also, attach an “id” attribute having a value of “example1”.
- Then, create a variable “example” inside the “<script>”. This variable holds the reference of the “h3” element using its id.
- Next, assign the “clientWidth” property with the “example” variable, and store it in the new variable named “exampleWidth”.
- After that, display the “exampleWidth” variable on the console using the “console.log()” method.
- First, select the “example” id inside the “<style>” tag to perform CSS properties.
- Next, set the value of “200px” and “50px” for the “width” and “padding” properties, respectively.
- After that, set values of “20px” and “lightgray” for the CSS “margin” and “background-color” properties for better visualization.
After the execution of the above code snippets, the webpage appears like this:
The output displays that the width of the select “h3” element is displayed. It includes “50px” of padding from both sides making a total of 100px and “200px” of width which is provided by the developer while styling the element.