The CSS Box Model describes how every element on a web page is built as a box: it has content, optional padding, a border, and a surrounding margin. Understanding this model is essential for controlling layout, spacing, and alignment in modern web design.
? Box = Content + Padding + Border + Margin
The total size of a box depends on its declared width and height, plus any padding, border, and margin. By default, the width and height apply only to the content area.
/* Generic box model syntax for any selector */
selector {
width: value;
height: value;
padding: value;
border: value;
margin: value;
}
Here is a simple example of a box that uses all four parts of the box model: width, height, padding, border, and margin.
/* A visible box using all key box model properties */
.box {
width: 300px;
height: 200px;
padding: 20px;
border: 5px solid #007bff;
margin: 30px;
}
By default, the declared width and height apply only to the content. Padding and border are added on top of that, which can make the box larger than expected. To make layout easier, you can use: box-sizing: border-box;
With border-box, the declared width and height include the content, padding, and border. This is very common in modern CSS layouts.
/* Make width and height include padding and border for all elements */
*,
*::before,
*::after {
box-sizing: border-box;
}
This box demonstrates the CSS Box Model with content, padding, border, and margin.
| Property | Description | Example |
|---|---|---|
width |
Defines the content width. | 300px, 50% |
height |
Defines the content height. | 200px, auto |
padding |
Space between content and border. | 20px |
border |
Defines a boundary around the box. | 1px solid #000 |
margin |
Space outside the box. | 20px |
box-sizing: border-box; across your project so widths and heights are easier to reason about.total = width + left padding + right padding + left border + right border.margin to create space between elements, and padding to create space inside elements.%, rem) for width and margin..card class with different padding, border, and margin values. Observe how each property affects the spacing around and inside the card.width on a box and experiment with increasing padding and border both with and without box-sizing: border-box;.