Total width of element (including padding and border) in jQuery
Anyone else stumbling upon this answer should note that jQuery now (>=1.3) has outerHeight
/outerWidth
functions to retrieve the width including padding/borders, e.g.
$(elem).outerWidth(); // Returns the width + padding + borders
To include the margin as well, simply pass true
:
$(elem).outerWidth( true ); // Returns the width + padding + borders + margins
looks like outerWidth is broken in the latest version of jquery.
The discrepancy happens when
the outer div is floated, the inner div has the width set (smaller than the outer div) the inner div has style="margin:auto"
[Update]
The original answer was written prior to jQuery 1.3, and the functions that existed at the time where not adequate by themselves to calculate the whole width.
Now, as J-P correctly states, jQuery has the functions outerWidth and outerHeight which include the border
and padding
by default, and also the margin
if the first argument of the function is true
[Original answer]
The width
method no longer requires the dimensions
plugin, because it has been added to the jQuery Core
What you need to do is get the padding, margin and border width-values of that particular div and add them to the result of the width
method
Something like this:
var theDiv = $("#theDiv");
var totalWidth = theDiv.width();
totalWidth += parseInt(theDiv.css("padding-left"), 10) + parseInt(theDiv.css("padding-right"), 10); //Total Padding Width
totalWidth += parseInt(theDiv.css("margin-left"), 10) + parseInt(theDiv.css("margin-right"), 10); //Total Margin Width
totalWidth += parseInt(theDiv.css("borderLeftWidth"), 10) + parseInt(theDiv.css("borderRightWidth"), 10); //Total Border Width
Split into multiple lines to make it more readable
That way you will always get the correct computed value, even if you change the padding or margin values from the css