To get the full size of the space an element takes up, we can use
HTMLElement.offsetWidth. These properties of an element provide values that include the width of scrollbars, padding, and border.
// Grab an element with id target var element = document.getElementById('target'); // Check its height and width console.log('h', element.offsetHeight); console.log('w', element.offsetWidth);
Another way to achieve these same measurements is using
getBoundingClientRect() but that function would not provide accurate readings if transforms were applied to the element in question. It's better to get in the habit of using
offsetWidth for this because those properties account for transforms applied to our element.
Instead of getting the full size of an element, we might be interested in looking at the size of its content. Here's a method that ignores borders, margins, and scrollbars:
Element.clientWidth. These properties provide the dimensions of an element's content including padding.
// Log the height of visible content & padding console.log('h', element.clientHeight); // Log the width of visible content & padding console.log('w', element.clientWidth);
We can also look at the size of the content regardless of how much is currently visible onscreen.
Element.scrollWidth provide the height and width of the content--all of the content, even if scroll bars are in use and not all the content is currently in view.
// Log full height of content console.log('h', element.scrollHeight); // Log full width of content console.log('w', element.scrollWidth);
These are just some tiny techniques that you might need down the line. Keep them on your toolbelt and use them to build something! For example, you could store an element's height and width in data attributes when the document loads, and write CSS rules that attenuate to those data attributes to change the style of elements based on size. Another example where this stuff might be useful is finding the center of an element; we can get the element's height and width and divide those in half. You'll find little ways to use these techniques the more you practice and learn.