Box Model
Overview
The CSS Box Model is the foundational physics engine of web layout. Every single element rendered on a webpage (even if it visually looks like a circle or text) is mathematically calculated as a strict rectangular box. This box consists of four distinct layers radiating outward from the center: the Content area (the actual text or image), the Padding (transparent inner spacing), the Border (the visible outer wall), and the Margin (transparent outer spacing pushing other elements away).
Syntax
/* The CSS Box Model properties applied to a div */
.box {
/* 1. Content Size */
width: 200px;
height: 100px;
/* 2. Padding (Inner spacing: between content and border) */
padding: 20px;
/* 3. Border (The visible wall) */
border: 5px solid black;
/* 4. Margin (Outer spacing: pushing neighbors away) */
margin: 30px;
}Common Pitfalls
- Forgetting that background colors stretch behind the Padding AND the Border, but completely stop at the Margin. Margins are always 100% transparent and will show the parent container's background.
- Misunderstanding how default width math works. If you set
width: 200px,padding: 20px, andborder: 5px, the final rendered width on screen is NOT 200px. It is 250px (200 + 20left + 20right + 5left + 5right). This is why layouts often break unexpectedly.
Interview Questions
1. Content: The core data/text. 2. Padding: Transparent space inside the box, pushing the border outward. 3. Border: The perimeter stroke. 4. Margin: Transparent space outside the box, pushing neighboring elements away.
Real-World Example
Using padding and margin to create a cleanly spaced, clickable button.
.button {
/* Give the text room to breathe inside the button */
padding: 12px 24px;
/* The visible boundary */
border: 2px solid #000;
/* Ensure the button doesn't smash into the text below it */
margin-bottom: 16px;
}Check Your Knowledge
Test your understanding of Box Model with these quick questions.