Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript getBoundingClientRect() vs offsetHeight while calculate element height

Tags:

javascript

What is the best way to get element height:

var myElement = document.querySelector('.some-class');

var height = myElement.getBoundingClientRect().height;

or

var myElement = document.querySelector('.some-class');

var height = myElement.offsetHeight;  
like image 778
haravares Avatar asked Apr 21 '17 08:04

haravares


People also ask

What is difference between offsetHeight and clientHeight?

clientHeight = the height of an element + the vertical padding. offsetHeight = the height of the element + the vertical padding + the top and bottom borders + the horizontal scrollbar (if it's available).

What is offsetHeight in Javascript?

The HTMLElement. offsetHeight read-only property returns the height of an element, including vertical padding and borders, as an integer. Typically, offsetHeight is a measurement in pixels of the element's CSS height, including any borders, padding, and horizontal scrollbars (if rendered).

Does Getboundingclientrect include margin?

margin is not included.


1 Answers

Most of the time these are the same as width and height of getBoundingClientRect(), when there aren't any transforms applied to the element. In case of transforms, the offsetWidth and offsetHeight returns the element's layout width and height, while getBoundingClientRect() returns the rendering width and height. As an example, if the element has width: 100px; and transform: scale(0.5); the getBoundingClientRect() will return 50 as the width, while offsetWidth will return 100.

https://developer.mozilla.org/en-US/docs/Web/API/CSS_Object_Model/Determining_the_dimensions_of_elements

like image 94
Hoijof Avatar answered Oct 11 '22 17:10

Hoijof