The CSS Box Model
Every element on a web page is a box. In the middle sits the content. Around it comes padding, then a border, then margin. Together these four layers are the box model. The box model decides how wide an element really is, how much space it needs, and how far it sits from its neighbors.
Padding is space inside the border, between the border and the content. Margin is space outside the border, between the border and other elements. Padding gives a button its shape; margin gives a page its rhythm. Both accept shorthand values, like padding: 10px 20px, where the first value is top and bottom and the second is left and right.
Here is the part that trips people up: by default, width sets the width of the content only. Padding and border are added on top. A div with width 200px, padding 20px, and a 4px border is actually 248px wide. That is why so many sites start with box-sizing: border-box, which makes width include padding and border.
The math behind the box
By default, the width property sets the content width only. The rendered width is content plus padding plus border. A div with width 240px, padding 24px on each side, and a 6px border is 240 + 48 + 12, which is 300px wide. Height works the same way. Newcomers set width: 200px, add padding, and wonder why the layout overflows. The math is doing exactly what it was told.
.box {
width: 240px;
padding: 24px;
border: 6px solid #1e40af;
}
/* rendered width = 240 + 48 + 12 = 300px */
border-box fixes the surprise
box-sizing: border-box makes width and height include padding and border. The 240px div above stays 240px, and the padding eats into the content space instead of adding to it. That is why nearly every stylesheet starts with * { box-sizing: border-box; }. Apply it globally once, and the box model stops surprising you for the rest of your career.
* {
box-sizing: border-box;
}
/* now width: 240px means 240px total, padding included */
Margin collapse
Vertical margins collapse. When two boxes stack, their top and bottom margins do not add up; the browser keeps only the larger one. Two paragraphs with margin: 30px 0 sit 30px apart, not 60px. Horizontal margins never collapse. Padding and borders never collapse either, so collapsing is a quirk of vertical margins only. Expect it, and you will never chase a phantom gap again.
p {
margin: 30px 0;
}
/* stacked paragraphs keep 30px between them, not 60px */
Syntax
div {
width: 200px;
padding: 20px;
border: 4px solid #0d9488;
margin: 30px;
}
width:200px + padding 20px = 240px (Default)
By default width counts content only — padding and border add on top. Use *{box-sizing:border-box} to include them.
*{box-sizing:border-box}
Good to know
- The box model is content, padding, border, and margin, from the inside out.
- Width counts only content unless you use border-box.
- Vertical margins collapse; horizontal margins do not.
- Start stylesheets with box-sizing: border-box.