The CSS Box Model
The box model describes how elements are sized and spaced. Every element is a box with content, padding, border, and margin areas.
Box Model Components
Content: The actual content (text, images, etc.) inside the element.
Padding: Space between content and border, inherits background.
Border: A line around the padding, can have width, style, and color.
Margin: Space outside the border, pushes other elements away.
Total element size = content + padding + border + margin.
/* Box model visualization */\n.box {\n /* Content area */\n width: 200px;\n height: 100px;\n \n /* Padding (inside border) */\n padding: 20px;\n \n /* Border */\n border: 5px solid black;\n \n /* Margin (outside border) */\n margin: 15px;\n \n /* Total width: 200 + 20*2 + 5*2 + 15*2 = 280px */\n /* Total height: 100 + 20*2 + 5*2 + 15*2 = 180px */\n}
Box Sizing Property
box-sizing: content-box (default) - width/height apply to content only.
box-sizing: border-box - width/height include padding and border.
border-box makes sizing more intuitive and is preferred for responsive design.
Most modern CSS frameworks apply border-box globally.
/* Content box (default) */\n.content-box {\n box-sizing: content-box;\n width: 300px;\n padding: 20px;\n border: 10px solid;\n /* Total width: 360px */\n}\n\n/* Border box (recommended) */\n.border-box {\n box-sizing: border-box;\n width: 300px;\n padding: 20px;\n border: 10px solid;\n /* Total width: 300px (padding/border included) */\n}\n\n/* Apply globally */\n*,\n*::before,\n*::after {\n box-sizing: border-box;\n}