🚀 Ultimate JavaScript DOM Cheat Sheet (Free PDF) 👉 Get the PDF ×

JavaScript Tutorials

JavaScript

JavaScript Get Width Of Element new

JavaScript Change Background Color new

JavaScript CLASS Attribute

JavaScript GET Class Names new

JavaScript ADD Class To Element new

JavaScript CHANGE Class new

JavaScript TOGGLE Class new

JavaScript REMOVE Class From Element new

JavaScript Modules

JavaScript Import Function From Another File new

JavaScript Cannot use import statement outside a module new

JavaScript Defer or Async

JavaScript DOM

JavaScript Get Element By ID new

JavaScript Get Elements By Class Name new

JavaScript Get Elements By Tag Name new

JavaScript Get Elements By Name new

JavaScript HTMLCollection vs NodeList new

JavaScript append() new

JavaScript appendChild() new

JavaScript append() Vs appendChild() new

JavaScript Create HTML Element new

JavaScript Remove HTML Element new

JavaScript Functions

JavaScript Call A Function new

JavaScript Events

JavaScript Get ID of Clicked Element new

JavaScript e.target new

JavaScript Custom Pop-Up Modal Window new

JavaScript Make A Clicked Button Active new

JavaScript For Loop Click Event

JavaScript Images

JavaScript Create / Add Image

JavaScript Working With Images

JavaScript Image Slider

JavaScript Higher Order Functions

JavaScript Find()

JavaScript Filter() vs Find()

JavaScript Forms

JavaScript Radio Buttons

JavaScript Select Drop Down

JavaScript AJAX

JavaScript Fix CORS Error

JavaScript Menu

JavaScript Accordion Menu

JavaScript MVC

JavaScript MVC Part #1

JavaScript MVC Part #2

JavaScript MVC Part #3

Last modified on June 6th, 2024

Raja Tamil

15,293 views

0 Comments

Javascript

15,293

Learn how to get the width of an HTML element using different properties and methods in JavaScript.

  1. Using . innerWidth Property
  2. Using . offsetWidth Property
  3. Using . clientWidth Property
  4. Using . scrollWidth Property
  5. Using . getBoundingClientRect() Method

1. Using innerWidth

The innerWidth property only works on the window object to get the width of the browser’s viewport.

This property won’t work on any of the HTML element objects and will return undefined.

window.innerWidth; // returns width of the viewport

JavaScript

Copy

Make sure to check if the window object becomes available first before accessing the innerWidth of it.

Try it out

CodePen Embed - JavaScript Get Width of Element #1 Using innerWidth

Live

xxxxxxxxxx

9

Live

xxxxxxxxxx

8

JavaScript Get Width of Element #1 Using innerWidth

959

This Pen is owned by SoftAuthor on CodePen.

See more by @softauthor on CodePen

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.

2. Using offsetWidth

The offsetWidth property returns the total amount of space of an element horizontally, including the width of the content, scrollbars (if any), padding, and border.

That is something we won’t be able to do with innerWidth as it only works on the window object.

Here is the simple div element that has an id called box.

<div id="box"></div>

HTML

Copy

Here is the CSS style for the box element.

#box {
  width:100px;
  padding:5px;
  border:5px solid blue;
  height:100px;
  margin:10px;
}

CSS

Copy

In order to get the width of it, first we need to get the DOM reference of the element object.

Call getElementById() method on the document object passing the box string as an argument.

It returns the box element object and assigns it to the constant box.

const box = document.getElementById("box");
console.log(box.offsetWidth); // 120 (100 width + 10 border + 10 padding)

JavaScript

Copy

The offsetWidth property on the element object will return the actual element width.

In this case, it’ll be 120.

When using the offsetWidth property, it will add the following CSS properties to calculate the element width:

  • width – 100px specific in the CSS rule
  • border – 5px on both sides
  • padding – 5px on both sides

If we remove the border and padding, the offsetWidth property will return…

You’ve guessed it right… 100px

What if we do not give the width:100px inside the CSS rule?

In that case.. innerWidth will check two things:

  1. If it is a block-level element such as div, p, section , etc, or an inline element such as span, strong, etc.
  2. If any content is inside that element.

If there is no content and no width specified in an HTML element, the innerWidth property returns 0.

If the element is block level with some content in it, the innerWidth property will return the full width of the viewport.

Normally a block-level element will fill the width of its parent element as soon as we add some content to it.

If the width of the block-level element is specified inside the CSS rule, the innerWidth property will return just that…of course including the padding and border.

On the other hand, when the inline HTML element has some content in it, the innerWidth will return the width of the element based on its content size.

If you want to add width to the inline HTML element via CSS, you’ll need to convert it to an inline block first by adding display:inline-block CSS property.

Only then, the value of the width property specified in CSS will be effective on the inline elements such as span, strong, etc.

The innerWidth won’t consider margin or scrollbar widths when it calculates the width of an element.

Try it out

codepen.io

codepen.io is blocked

codepen.io refused to connect.

ERR_BLOCKED_BY_RESPONSE

codepen.io refused to connect.

3. Using clientWidth

The clientWidth returns how much an element takes up horizontally, including padding but not including the border, margins, or scrollbars.

The clientWidth property is very similar to offsetWidth.

The only difference is that the clientWidth will ignore the border width when it calculates the width of an element.

It only returns the sum of the width and padding and ignores the border width.

const box = document.getElementById("box");
console.log(box.clientWidth); // 110 (100 width + 10 padding) & ignores border

JavaScript

Copy

Whereas the offsetWidth will return the sum of the width, padding, and border.

Try it out

codepen.io

codepen.io is blocked

codepen.io refused to connect.

ERR_BLOCKED_BY_RESPONSE

codepen.io refused to connect.

4. Using scrollWidth

The scrollWidth returns the actual size of the content, regardless of how much of it is currently visible.

It returns inner div width + inner div padding + outer div padding.

Here is a parent div with an id box that has a width of 100 pixels. It has a child div element with an id inner-box.

The inner div has a width of 500px.

<div id="box">
    <div id="inner-box">
    </div>
</div>

HTML

Copy

I’ve also set the overflow property to the parent div as the inner div content width is greater than the parent div.

#box {
  width:100px;
  padding:5px;
  height:100px;
  overflow:scroll;
}

#inner-box {
  width:500px;
  padding:5px;
}

CSS

Copy

When you access the scrollWidth property on the parent div element, it returns 520 pixels.

When using the scrollWidth property, it will add the following CSS properties to calculate the element width:

  • The width of the inner element if it’s greater than the parent – 500px
  • Padding of the parent element – 10px (both left and right sides)
  • Padding of the child element – 10px (both left and right sides)
const box = document.getElementById("box");
console.log(box.scrollWidth); // 520 (500 inner box width + 10 inner box padding + 10 outbox padding )

JavaScript

Copy

Try it out

codepen.io

codepen.io is blocked

codepen.io refused to connect.

ERR_BLOCKED_BY_RESPONSE

codepen.io refused to connect.

5. Using getBoundingClientRect()

The getBoundingClientRect() method will return the DOMRect object.

The DOMRect object has information about the location and dimension of the element as floating numbers after completing the CSS transforms.

We can easily get the width by accessing the width property on the DOMRect object.

const box = document.getElementById('box');
const boxRect = box.getBoundingClientRect();
console.log(boxRect.width); // 110 (100 width + 10 border) and ignores padding

JavaScript

Copy

The width of the element includes the actual width specified in the CSS or content width PLUS border on both right and left sides PLUS padding on both sides.

codepen.io

codepen.io is blocked

codepen.io refused to connect.

ERR_BLOCKED_BY_RESPONSE

codepen.io refused to connect.

The getBoundingClientRect() method returns an object that has the following properties:

  • height – the height of the element including the actual height specified in the CSS + the border on both sides and ignores the padding.
  • x– horizontal location of the element on the viewport
  • y – vertical location of the element on the viewport
  • left – left side location of the element on the viewport
  • right – right side location of the element on the viewport
  • top – right side location of the element on the viewport
  • bottom – bottom side location of the element on the viewport
.innerWidth .offsetWidth .clientWidth .scrollWidth getBoundingClientRect()
window 🛑 🛑 🛑 🛑
width
padding 🛑
border 🛑 🛑 🛑

Disqus Recommendations

We were unable to load Disqus Recommendations. If you are a moderator please see our troubleshooting guide.

  • 8 months ago

In this FREE course, you're going to learn how to build a simple real-world …

  • 3 years ago

Learn how to get use data from firebase 9 Cloud Firestore database with 3 …

  • 3 years ago

Learn how to use createUserWithEmailAndPassword() to create a new Firebase …

  • 3 years ago

Learn how to sign out or log out users of their current authentication using …

  • 4 months ago

Learn how to model Firestore data the right way for performance, cost, and …

  • 3 years ago

Learn how to authenticate a user account using the …

  • 3 years ago
  • 1 comment

The onAuthStateChanged() method is triggered when a user's authentication state …

tempest.services.disqus.com

tempest.services.disqus.com is blocked

This page has been blocked by an extension

  • Try disabling your extensions.

ERR_BLOCKED_BY_CLIENT

Reload

This page has been blocked by an extension

Disqus Comments

We were unable to load Disqus. If you are a moderator please see our troubleshooting guide.

G

Start the discussion…

Comment

Log in with
or sign up with Disqus or pick a name

Disqus is a discussion network

  • Don't be a jerk or do anything illegal. Everything is easier that way.

Read full terms and conditions

This comment platform is hosted by Disqus, Inc. I authorize Disqus and its affiliates to:

  • Use, sell, and share my information to enable me to use its comment services and for marketing purposes, including cross-context behavioral advertising, as described in our Terms of Service and Privacy Policy, including supplementing that information with other data about me, such as my browsing and location data.
  • Contact me or enable others to contact me by email with offers for goods or services
  • Process any sensitive personal information that I submit in a comment. See our Privacy Policy for more information

Acknowledge I am 18 or older

Favoriting means this is a discussion worth sharing. It gets shared to your followers' Disqus feeds, and gives the creator kudos!

Find More Discussions

Share

  • Tweet this discussion

    • Share this discussion on Facebook
    • Share this discussion via email
    • Copy link to discussion
  • Best

Be the first to comment.

Load more comments

live.rezync.com

live.rezync.com is blocked

This page has been blocked by an extension

  • Try disabling your extensions.

ERR_BLOCKED_BY_CLIENT

Reload

This page has been blocked by an extension

pippio.com

pippio.com is blocked

This page has been blocked by an extension

  • Try disabling your extensions.

ERR_BLOCKED_BY_CLIENT

Reload

This page has been blocked by an extension

Twitter Widget Iframe