HTML DOM clientHeight Property
clientHeight = inner height + padding
Here’s an example.
<body> <div id='cont' style='width: 50%; border: solid 3px #f47512; height: 90px; padding: 5px 7px; overflow: auto;'> </div> </body> <script> var cont = document.getElementById('cont'); var ch = cont.clientHeight; document.getElementById('result').innerHTML = 'height + padding (top and bottom) = ' + ch; // Using ES6 features. // let cont = document.getElementById('cont'); // let ch = cont.clientHeight; // document.getElementById('result').innerHTML = 'height + padding (top and bottom) = ' + ch; </script>
I have defined few CSS properties like height, padding and border to the <div> element in the example. In-addition, the overflow property is auto, so it will show a scrollbar.
The clientHeight property (inside the script section) will return a value (a numeric value) in pixels (or px), which is the height + padding.
height = 90px (see inline style of the <div>)
+
top-padding = 5px and bottom-padding = 5px, which is 10px
The clientHeight, in this case is 100px.
HTML DOM offsetHeight Property
offsetHeight = inner height + padding + border + scrollbar height
See this example.
<body> <div id='cont' style='width: 50%; border: solid 3px #f47512; height: 90px; padding: 5px 7px; overflow: auto;'> </div> </body> <script> var cont = document.getElementById('cont'); var osh = cont.offsetHeight; document.getElementById('result').innerHTML = 'height + padding (top and bottom) + scrollbar + border (top and bottom) = ' + osh; // Using ES6 features. // let cont = document.getElementById('cont'); // let ch = cont.clientHeight; // document.getElementById('result').innerHTML = 'height + padding (top and bottom) = ' + ch; </script>
In this case the result will be,
height = 90px (see inline style of the <div>)
+
top-padding = 5px and bottom-padding = 5px, which is 10px
+
scrollbar height
+
border-top = 1.5px and border-bottom = 1.5p, which is 3px
The offsetHeight, in this case is 106px.
You can also try
The best way to understand more about the above-mentioned properties is to experiment with different value. For example,
1) Remove the element’s CSS height property and see the result.
2) Alter the border size, padding and margin etc. and see the result.
Where should I use these properties?
You can use the above-mentioned properties, along with the clientWidth and offsetWidth properties to create amazing web pages.
I have used the clientHeight and offsetHeight properties to create a sticky <div> on my blog’s home and other pages. If you have visited the home page, you must have noticed a sticky vertical <div> section (on the right side) while scrolling down and up the page.
While you scroll down or up the page, the element remains fixed until it reaches a particular point. I am using the element to show Google ads and I wanted the <div> to be visible for a longer period while the user browses the page.