CSS Box Model
Every HTML element is a rectangular box made of content, padding, border, and margin, from innermost to outermost. This is the CSS box model.
Understanding the box model is essential for controlling layout, spacing, and sizing accurately.
box-sizing: border-box;The four layers
Content holds text/images. Padding surrounds content. Border wraps padding. Margin is outside the border, separating from other elements.
box-sizing property
By default (content-box), width/height apply only to content, and padding/border add extra size. box-sizing: border-box includes padding and border within the declared width/height.
* {
box-sizing: border-box;
}
.box {
width: 200px;
padding: 20px;
border: 5px solid black;
}A box that is exactly 200px wide total, including padding and borderborder-box makes the declared width include padding and border, simplifying layout math.
Key points
- The box model layers are content, padding, border, and margin.
- Default box-sizing is content-box.
- border-box includes padding/border in the width calculation.
- Applying box-sizing: border-box globally is a common best practice.
