CSS box-sizing content-box Calculation Guide

In CSS, box-sizing: content-box is the default box model behavior that determines how a browser calculates an HTML element's total rendered dimensions. This article explains the underlying mathematical formula of the content-box model, illustrates how padding, borders, and margins influence an element's final footprint, and highlights the practical implications of this calculation in web layout design.

The Core Principle of content-box

Under box-sizing: content-box, any explicit width or height applied to an element via CSS applies exclusively to the element's content area. It does not account for padding, borders, or margins. As a result, adding padding or borders increases the total visible size of the element on the screen beyond the specified dimensions.

The Calculation Formula

To determine the final rendered size of an element using content-box, the browser sums the content size, padding, and border widths:

  • Rendered Width: width + padding-left + padding-right + border-left-width + border-right-width
  • Rendered Height: height + padding-top + padding-bottom + border-top-width + border-bottom-width

Margins are not part of the element's visible box, but they determine the total space the element occupies in the document flow:

  • Total Space (Width): Rendered Width + margin-left + margin-right
  • Total Space (Height): Rendered Height + margin-top + margin-bottom

Practical Example

Consider an element with the following CSS rules:

.box {
  box-sizing: content-box;
  width: 300px;
  height: 150px;
  padding: 20px;
  border: 4px solid #000;
  margin: 10px;
}

The browser computes the dimensions step-by-step:

  1. Content Area: 300px wide by 150px tall.
  2. Padding Addition: 20px on all sides adds 40px to both width and height.
  3. Border Addition: 4px on all sides adds 8px to both width and height.
  4. Rendered Visible Width: 300px + 20px + 20px + 4px + 4px = 348px
  5. Rendered Visible Height: 150px + 20px + 20px + 4px + 4px = 198px
  6. Total Document Footprint: 368px wide by 218px tall (including the 10px margins).

Even though the CSS specifies width: 300px, the browser renders a box that is 348px wide.

Key Implications for Web Layouts

  • Unexpected Overflow: Setting an element to width: 100% alongside padding or borders will cause the element to exceed its parent container's width, often producing unwanted horizontal scrollbars.
  • Complex Grid Calculations: Creating multi-column layouts requires subtracting padding and border values manually or using CSS calc() functions to keep columns from wrapping onto new lines.
  • Alternative Solution: Because this additive behavior can complicate responsive layouts, modern CSS workflows often reset elements globally to box-sizing: border-box, where specified widths absorb both padding and borders.