0
0
CSSmarkup~5 mins

Box sizing in CSS

Choose your learning style9 modes available
Introduction

Box sizing controls how the size of an element is calculated. It helps you decide if padding and borders are included in the width and height or added outside.

When you want to make sure an element fits exactly in a space without growing bigger because of padding or borders.
When you want consistent sizing for buttons or boxes, no matter their padding or border thickness.
When you want to avoid layout problems caused by padding or borders increasing the element size unexpectedly.
Syntax
CSS
box-sizing: content-box | border-box;
content-box is the default. Width and height apply only to the content area. Padding and border add extra size outside.
border-box includes padding and border inside the width and height, so the element size stays as you set it.
Examples
The total size will be 200px (content) + 40px (padding) + 10px (border) = 250px wide.
CSS
div {
  box-sizing: content-box;
  width: 200px;
  padding: 20px;
  border: 5px solid black;
}
The total size stays 200px wide. Padding and border are inside that 200px.
CSS
div {
  box-sizing: border-box;
  width: 200px;
  padding: 20px;
  border: 5px solid black;
}
Sample Program

This page shows two boxes. The first uses content-box, so padding and border add to the width. The second uses border-box, so the total width stays 200px. You can see how the boxes differ in size.

CSS
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Box Sizing Example</title>
  <style>
    .box {
      width: 200px;
      padding: 20px;
      border: 5px solid #333;
      margin-bottom: 20px;
      background-color: #cce5ff;
      font-family: Arial, sans-serif;
    }
    .content-box {
      box-sizing: content-box;
    }
    .border-box {
      box-sizing: border-box;
    }
  </style>
</head>
<body>
  <h1>Box Sizing Demo</h1>
  <div class="box content-box">
    <strong>content-box</strong><br />
    Width set to 200px.<br />
    Padding and border add extra size.<br />
    Total width is 250px.
  </div>
  <div class="box border-box">
    <strong>border-box</strong><br />
    Width set to 200px.<br />
    Padding and border inside width.<br />
    Total width stays 200px.
  </div>
</body>
</html>
OutputSuccess
Important Notes

Using border-box often makes layout easier because sizes stay consistent.

You can set box-sizing: border-box; globally with * { box-sizing: border-box; } to simplify styling.

Summary

Box sizing controls if padding and border are inside or outside the width and height.

content-box adds padding and border outside the size.

border-box keeps padding and border inside the size, making layout easier.