How to Include Margin in jQuery outerWidth

This article explains how to include an element's CSS margins when calculating its total horizontal dimension using jQuery. By default, the outerWidth() method measures the width of an element including its padding and border, but excludes the margins. You will learn the exact syntax, parameter requirements, and practical code examples needed to include margins in your layout calculations.


The Solution: Pass true as an Argument

To include margins in the calculation, pass the boolean value true to the .outerWidth() method:

let totalWidth = $('#myElement').outerWidth(true);

How jQuery Width Methods Compare

jQuery provides several methods to measure the horizontal dimensions of an element. Understanding the differences helps clarify what .outerWidth(true) computes:

  • .width(): Content width only (excludes padding, border, and margin).
  • .innerWidth(): Content + horizontal padding.
  • .outerWidth() (or .outerWidth(false)): Content + horizontal padding + horizontal border.
  • .outerWidth(true): Content + horizontal padding + horizontal border + horizontal margin (left and right margins).

Example Implementation

Consider an element styled with the following CSS:

#box {
  width: 200px;
  padding: 15px;      /* 15px left + 15px right = 30px */
  border: 5px solid;  /* 5px left + 5px right = 10px */
  margin: 20px;       /* 20px left + 20px right = 40px */
  box-sizing: content-box;
}

Using jQuery to measure this element yields different values based on the argument provided:

// Returns 240 (200 + 30 + 10)
let widthWithoutMargin = $('#box').outerWidth();

// Returns 280 (200 + 30 + 10 + 40)
let widthWithMargin = $('#box').outerWidth(true);

console.log('Without margin:', widthWithoutMargin);
console.log('With margin:', widthWithMargin);

Important Considerations

  • Hidden Elements: If an element or its parent has display: none;, jQuery temporarily displays the element off-screen to compute dimensions, but it is best practice to ensure the element is rendered in the DOM to avoid unexpected zero values.
  • Box-Sizing: The outerWidth(true) method calculates the actual space the element occupies in the document flow regardless of whether the element uses box-sizing: content-box or box-sizing: border-box.
  • Vertical Dimension: The identical logic applies to vertical measurements using .outerHeight(true), which includes the top and bottom margins.