Difference Between jQuery innerWidth() and width()
Understanding the distinction between jQuery's width()
and innerWidth() methods is essential for accurate layout
calculations and DOM manipulation. While both methods measure the
horizontal dimension of an HTML element, they measure different segments
of the CSS box model. This guide breaks down the structural differences
between these two methods, demonstrates how padding alters their
outputs, and clarifies when to use each in your projects.
The Core Difference: The CSS Box Model
To understand the difference between width() and
innerWidth(), you must consider the four components of the
standard CSS box model: content, padding, border, and margin.
width(): Measures only the content area of the element. It excludes padding, borders, and margins.innerWidth(): Measures the content area plus the left and right padding. It excludes borders and margins.
Mathematical Breakdown
width()= Content WidthinnerWidth()= Content Width + Left Padding + Right Padding
Practical Example
Consider a div element styled with the following
CSS:
.box {
width: 300px;
padding: 20px;
border: 5px solid black;
margin: 10px;
box-sizing: content-box;
}Applying the jQuery methods to this element produces different values:
// Returns 300 (content only)
$('.box').width();
// Returns 340 (300 content + 20 left padding + 20 right padding)
$('.box').innerWidth();If the element uses box-sizing: border-box, the rendered
content area automatically shrinks to accommodate padding and borders,
but the calculation rule remains the same: width() will
return the computed content-only width, and innerWidth()
will return that content width plus the horizontal padding.
Setter Behavior
Both methods can also be used as setters:
$('selector').width(value): Sets the width of the content area directly.$('selector').innerWidth(value): Introduced in jQuery 1.8, this adjusts the element's width so that the total width including padding equals the specified value.
When to Use Each Method
- Use
width()when you need to read or alter the raw content dimension without factoring in internal spacing. This is standard when applying programmatic sizing that aligns strictly with CSSwidthrules. - Use
innerWidth()when calculating available interior space for child elements, positioning elements inside a padded container, or calculating scroll boundaries where padding affects visible overflow.