Box Model in CSS
? CSS Box Model — Explained
The CSS Box Model is the foundation of layout and design on the web. It describes how elements are wrapped and spaced inside their containers.
Components of the Box Model
Every HTML element is a rectangular box composed of these parts (from inside out):
| Part | Description |
|---|---|
| Content | The actual content (text, image, etc.) |
| Padding | Space between content and border |
| Border | The border surrounding the padding |
| Margin | Space outside the border, separating elements |
Visual representation:
+------------------------------+| Margin || +------------------------+ || | Border | || | +------------------+ | || | | Padding | | || | | +------------+ | | || | | | Content | | | || | | +------------+ | | || | +------------------+ | || +------------------------+ |+------------------------------+Key CSS properties:
width/height— size of the content area by defaultpadding— space inside the borderborder-width— thickness of the bordermargin— space outside the border
Default box-sizing behavior
By default, width and height apply only to the content. Padding and border add extra size:
div { width: 200px; padding: 20px; border: 5px solid black; margin: 10px;}/* Total element width = 200 + 20*2 + 5*2 = 250px */Using box-sizing
Set box-sizing: border-box to include padding and border inside width and height:
div { box-sizing: border-box; width: 200px; padding: 20px; border: 5px solid black;}/* Total element width = exactly 200px */This often makes layouts easier to manage.
Summary:
| Property | What it affects | Inside/Outside width |
|---|---|---|
content | Content box size | Inside |
padding | Inner spacing | Outside (default) |
border | Border thickness | Outside (default) |
margin | Outer spacing | Outside |
Example:
.box { width: 300px; padding: 20px; border: 10px solid gray; margin: 15px; box-sizing: border-box; /* Include padding and border inside width */}Want me to show how box model affects layout visually with code snippets or how to debug spacing issues?