Skip to content

Instantly share code, notes, and snippets.

@joepie91
Last active June 25, 2023 09:05
Show Gist options
  • Save joepie91/5ffffefbf24dcfdb4477 to your computer and use it in GitHub Desktop.
Save joepie91/5ffffefbf24dcfdb4477 to your computer and use it in GitHub Desktop.
How to get the actual width of an element in jQuery, even with border-box: box-sizing;

This is ridiculous, but per the jQuery documentation:

Note that .width() will always return the content width, regardless of the value of the CSS box-sizing property. As of jQuery 1.8, this may require retrieving the CSS width plus box-sizing property and then subtracting any potential border and padding on each element when the element has box-sizing: border-box. To avoid this penalty, use .css( "width" ) rather than .width().

function parsePx(input) {
let match;
if (match = /^([0-9+])px$/.exec(input)) {
return parseFloat(match[1]);
} else {
throw new Error("Value is not in pixels!");
}
}
$.prototype.actualWidth = function() {
/* WTF, jQuery? */
let isBorderBox = (this.css("box-sizing") === "border-box");
let width = this.width();
if (isBorderBox) {
width = width
+ parsePx(this.css("padding-left"))
+ parsePx(this.css("padding-right"))
+ parsePx(this.css("border-left-width"))
+ parsePx(this.css("border-right-width"));
}
return width;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment