The .width() method gets or sets the width of matched elements as a unitless pixel Number — ideal for math and animations. This tutorial covers getter and setter overloads, comparisons with .css("width"), .height(), .innerWidth(), and .outerWidth(), window and document widths, and practical bar-chart and responsive sidebar patterns.
01
Getter
.width() → Number
02
Setter
String or Number
03
vs css()
Number vs string
04
inner/outer
Padding & border
05
Callback
Since 1.4.1
06
Since 1.0
Core API
Fundamentals
Introduction
After learning to read and write CSS with .css(), you often need a simpler way to work with element dimensions — especially width. jQuery’s .width() returns a plain number you can multiply, add, or pass directly to .animate(), without parsing "400px" strings.
Available since jQuery 1.0, .width() works as both a getter (no arguments) and a setter (value or callback). The getter reads the content width of the first matched element; the setter applies a new width to every element in the set. It also works on $(window) and $(document) for viewport and page measurements.
Concept
Understanding the .width() Method
Given a jQuery object, .width() either returns the current content width of the first matched element as a unitless pixel Number (getter), or sets the CSS width property on every matched element (setter). Unlike .css("width"), the getter never returns a string with units — it is ready for arithmetic.
Think of .width() as a specialized ruler for the horizontal content box. .innerWidth() extends the ruler through padding; .outerWidth() includes border (and optionally margin). Use .width() when you need clean numbers; reach for .css() when you need percentage widths, auto, or other CSS values.
💡
Beginner Tip
var w = $("div").width() gives you a Number like 400. $("div").css("width") gives you a String like "400px". For w * 2 or .animate({ width: w }), use .width().
Foundation
📝 Syntax
jQuery .width() has three argument forms — one getter and two setters:
Get — no arguments (since 1.0)
jQuery
.width() // -> Number
Returns the content width of the first matched element as a unitless pixel Number.
Works on elements, $(window), and $(document).
Equivalent to reading the inner content box — padding and border are excluded.
Set — String or Number (since 1.0)
jQuery
.width( value ) // -> jQuery
value — a pixel width as a Number (e.g. 50) or a String with units (e.g. "50%", "10em").
Numbers are treated as pixels and applied as inline width.
Returns the original jQuery object for chaining — e.g. .width(50).css("backgroundColor", "green").
Set — callback function (since 1.4.1)
jQuery
.width( function( index, width ) {
// return new width (Number or String)
} )
index — zero-based position of the element in the matched set.
width — current width of this element before the change.
Return a new width per element; jQuery applies it and returns the jQuery object.
Return value
Getter — unitless Number (pixels). May be fractional on sub-pixel layouts.
Setter — the original jQuery object for chaining.
Important note
⚠️
Hidden elements
.width() on display:none or hidden elements is unreliable — jQuery may return 0. Measure after showing the element, clone it off-screen, or use a visibility trick before reading. Avoid calling .width() on style or script tags.
Official jQuery API example
jQuery
function showWidth( element, width ) {
$( "div" ).text( "The width for the " + element + " is " + width + "px." );
}
showWidth( "paragraph", $( "p" ).width() );
showWidth( "document", $( document ).width() );
showWidth( "window", $( window ).width() );
Cheat Sheet
⚡ Quick Reference
Goal
Code
Read element width (Number)
$("div").width()
Set width in pixels
$("div").width(400)
Set width with units
$("div").width("50%")
Per-element callback (1.4.1+)
$(".bar").width(function(i){ return 30 + i * 25; })
Viewport width
$(window).width()
Full page scroll width
$(document).width()
Include padding
$("div").innerWidth()
Include padding + border
$("div").outerWidth()
Compare
📋 .width() vs .css() vs .height() vs .innerWidth() vs .outerWidth()
Five dimension methods — content box, CSS strings, vertical twin, and padding/border variants.
.width()
content W
Get/set content width — returns unitless Number
.css()
"400px"
General CSS getter/setter — width returns String with units
.height()
content H
Vertical twin of .width() — same getter/setter pattern
.innerWidth()
+ pad
Content width plus padding — getter only on elements
.outerWidth()
+ border
Includes padding and border; pass true to add margin
Hands-On
Examples Gallery
Examples 1–2 follow the official jQuery API documentation. Examples 3–5 compare .css(), demonstrate callback setters, and build a responsive sidebar. Use DevTools or the Try-it links to run each snippet.
📚 Getting Started
Official jQuery demos for reading and setting width.
Example 1 — Official Demo: Get Paragraph, Document, and Window Width
Three buttons read widths from a paragraph, the full document, and the viewport.
Get Paragraph Width -> "The width for the paragraph is 150px."
Get Document Width -> full scrollable page width in px
Get Window Width -> visible viewport width in px
How It Works
No-argument .width() returns a unitless pixel Number. On elements it measures content width; on document it returns total page width; on window it returns the viewport.
Example 2 — Official Demo: Set Width on First Click
Click a red box once to shrink it and add the mod class — each box gets a slightly smaller width.
Click first box -> width shrinks to 50px, turns blue
Click second box -> width 42px; third 34px; and so on
.one() ensures the handler runs only once per box
How It Works
.width(modWidth) sets inline CSS width in pixels. The setter returns the jQuery object, so .addClass("mod") chains immediately afterward. The shared modWidth variable decrements after each click — matching the official jQuery demo.
📈 Practical Patterns
Compare dimension APIs, callback setters, and responsive layouts.
Example 3 — Compare .width() vs .css("width") for Math
See why the unitless Number from .width() is easier to calculate with.
.width() -> 400 (Number, unitless px)
.css("width") -> 400px (String with units)
Math: width * 2 -> 800px
No parseInt needed — multiply the Number directly
How It Works
.width() strips the unit and returns a Number. .css("width") returns the computed CSS string. For width * 2, use .width(); use parseInt(..., 10) only if you must read via .css().
Example 4 — Callback Bar Chart: index * 25 Widths
Each bar gets a wider width based on its index in the matched set.
Apply -> bar widths: 30px, 55px, 80px, 105px, 130px
Formula: 30 + index * 25 (index 0, 1, 2, 3, 4)
Callback runs once per .bar element
How It Works
Since jQuery 1.4.1, the callback setter receives index and the current width. Return a new value per element — ideal for horizontal bar charts and indexed layouts without a manual loop.
Example 5 — Responsive Sidebar from $(window).width()
Resize the viewport to switch sidebar width between mobile and desktop breakpoints.
$(window).width() returns the viewport width as a unitless Number — perfect for breakpoint checks. Set the sidebar with .width(sidebarW) and re-run on resize to keep layout in sync.
Applications
🚀 Common Use Cases
Responsive layouts — $(window).width() to size sidebars, columns, or modals to the viewport.
Scroll progress — $(document).width() vs $(window).scrollLeft() for horizontal read-progress bars.
Equal-width columns — read each column’s .width(), find the max, set all to match.
Horizontal bar charts — callback setter .width(function(i){ return base + i * step; }) for indexed bar widths.
Slide panels — measure with .width(), animate open/closed with .animate({ width: ... }).
Dynamic spacing — var w = $el.width(); $next.css("marginLeft", w + 10) without string parsing.
🧠 How .width() Reads and Writes Dimensions
1
Match target
jQuery object holds elements, window, or document.
Input
2
Detect mode
No args → getter. Value or function → setter on each element.
Route
3
Measure or apply
Getter reads content box via offsetWidth minus padding/border. Setter writes inline width.
DOM
4
📏
Return result
Getter → unitless pixel Number. Setter → same jQuery object for chaining.
Important
📝 Notes
Available since jQuery 1.0 — core dimension API alongside .height().
Getter returns a unitless pixel Number from the first matched element only.
Callback setter since 1.4.1 — function receives (index, width).
box-sizing: border-box affects CSS layout but .width() still reports the inner content box — jQuery handles this since 1.8.
Unreliable on hidden (display:none) elements — may return 0.
Values can be fractional (e.g. 400.5) on sub-pixel or zoomed displays.
Avoid calling .width() on style or script tags — results are unreliable.
Setter returns the original jQuery object — e.g. .width(50).css("color","white").
Compatibility
Browser Support
.width() has been part of jQuery since 1.0+. The callback setter arrived in 1.4.1+. It wraps cross-browser dimension reads (offsetWidth, clientWidth, window/document APIs) with no browser-specific quirks beyond jQuery itself.
✓ jQuery 1.0+
jQuery .width()
Supported in jQuery 1.x, 2.x, and 3.x across all modern browsers and IE with supported jQuery builds. Native equivalent: element.offsetWidth minus padding/border, or getBoundingClientRect().width — jQuery adds collection semantics, unitless Numbers, and setter chaining.
100%With jQuery loaded
Google ChromeAll versions · Desktop & Mobile
Full support
Mozilla FirefoxAll versions · Desktop & Mobile
Full support
Apple SafariAll versions · macOS & iOS
Full support
Microsoft EdgeAll versions · Chromium & Legacy
Full support
Internet ExplorerIE 6+ · Legacy environments
Full support
OperaAll modern versions
Full support
.width()Universal
Bottom line: Safe in any jQuery project. Use .width() for pixel math; use .css('width') for percentage or auto values.
Wrap Up
Conclusion
The jQuery .width() method gets or sets element width as a unitless pixel Number — the go-to dimension helper when you need math-ready values for layouts, animations, and comparisons. It complements .css(), which returns strings with units.
Remember the official demo: $( "p" ).width() reads content width, $( document ).width() measures the full page, and $( window ).width() returns the viewport. Use the callback form for per-element widths, and pair .width() with $(window).width() for responsive sidebar layouts.
Use .width() when you need a Number for math or .animate()
Use $(window).width() for viewport-based responsive layouts
Use the callback setter for per-element widths in one call
Reach for .innerWidth() or .outerWidth() when padding or border matters
Measure hidden content by temporarily showing or cloning off-screen
❌ Don’t
Parse .css("width") when .width() already returns a Number
Trust .width() on display:none elements — it may return 0
Assume .width() includes padding — use .innerWidth() instead
Call .width() on style or script tags
Expect the getter to read all matched elements — only the first
Forget that fractional values may need Math.round() for integer layout
Summary
Key Takeaways
Knowledge Unlocked
Six things to remember about .width()
Unitless pixels — ready for math.
6
Core concepts
#01
Getter
Number
Read
=02
Setter
px / %
Write
css03
vs css
String
Compare
fn04
Callback
1.4.1+
Index
win05
Window
Viewport
Measure
hide06
Hidden
Unreliable
Caveat
❓ Frequently Asked Questions
Calling .width() with no arguments is the getter — it returns the current width of the first matched element as a unitless Number (pixels). Calling .width(value) or .width(function) is the setter — it sets the CSS width on every matched element and returns the original jQuery object for chaining. The getter works on elements, $(window), and $(document); setters apply to elements only.
.width() is a dimension helper: it always returns an integer or fractional pixel value as a plain Number with no unit suffix — ready for math like width * 2. .css('width') is a general CSS getter that returns a string such as '400px', '50%', or 'auto'. For calculations and animations, prefer .width(); use .css('width') when you need the literal computed CSS value or non-pixel units.
.width() measures horizontal content width only — padding and border excluded, equivalent to clientWidth without scrollbar width. .height() is the vertical twin with the same getter/setter pattern. .innerWidth() includes horizontal padding; .outerWidth() includes padding and border (and optionally margin). All return unitless Numbers for getters; pick the method that matches the box edge you need to measure.
$(window).width() returns the viewport width — the visible browser window area in pixels. $(document).width() returns the full scrollable document width, including content wider than the viewport. Both return unitless Numbers. Use window width for responsive layouts and breakpoint logic; use document width for scroll-position math or progress indicators tied to page width.
.width() measures the content width only — the area inside padding and border. .innerWidth() includes horizontal padding; .outerWidth() includes padding and border (and optionally margin). When box-sizing: border-box is set, the CSS width property includes padding and border, but .width() still reports the inner content box — jQuery handles the subtraction since 1.8, so the numbers may not match what you wrote in CSS.
No — .width() on display:none or visibility:hidden elements is unreliable; jQuery may report 0 or an incorrect value because the element is not rendered. Temporarily show the element, clone it off-screen, or use .innerWidth() after making it visible to measure. Returned widths can be fractional (e.g. 400.5) on sub-pixel layouts or zoomed displays; round with Math.round() when you need integers for layout. Avoid calling .width() on style or script tags.
Did you know?
jQuery’s .width() has existed since version 1.0 — alongside .height() as one of the first dimension helpers. It deliberately returns a unitless Number so you can write $("div").width() * 2 without parseInt. The callback setter (1.4.1+) mirrors .css() and .height() — return a different width per index for horizontal bar charts and staggered layouts. Since jQuery 1.8, .width() always reports content width even when box-sizing: border-box is set — for the full box including padding, .innerWidth() adds roughly 16px on a typical padded element.