CSS Box Sizing

The box-sizing property in CSS defines how the total width and height of an element are calculated. It controls whether the width and height include padding and border or just the content.

Key Topics

Content Box

The default value for box-sizing is content-box. The width and height of the element include only the content, excluding padding and borders.

<style>
        .content-box-example {
            width: 200px;
            padding: 20px;
            border: 5px solid #007BFF;
            box-sizing: content-box;
            background-color: #F0F0F0;
        }
</style>
<div class="content-box-example">This box has content-box sizing.</div>

Explanation: The element's total width is calculated as width + padding + border, making the box larger than the specified width.

Border Box

With box-sizing: border-box, the width and height of the element include padding and border, making the element's total size consistent.

<style>
        .border-box-example {
            width: 200px;
            padding: 20px;
            border: 5px solid #007BFF;
            box-sizing: border-box;
            background-color: #F0F0F0;
        }
</style>
<div class="border-box-example">This box has border-box sizing.</div>

Explanation: The total width remains the same as the specified width, and the content area is adjusted to accommodate padding and border.

Global Box Sizing

Applying box-sizing: border-box globally ensures consistent sizing across all elements, which is a common best practice.

<style>
        *, *::before, *::after {
            box-sizing: border-box;
        }
        .global-box-sample {
            width: 300px;
            padding: 20px;
            border: 10px solid #28A745;
            background-color: #F0F0F0;
        }
</style>
<div class="global-box-sample">This box uses global border-box sizing.</div>

Explanation: The global box-sizing rule ensures all elements use border-box, reducing inconsistencies in layout calculations.

Key Takeaways

  • Content Box: Default value, where width and height include only content.
  • Border Box: Includes padding and border in the width and height.
  • Global Usage: Applying box-sizing: border-box globally simplifies layout management.
  • Consistency: border-box is recommended for predictable sizing.
  • Best Practice: Use a global rule for box-sizing to avoid layout inconsistencies.