๐ŸŽจ

The CSS Box Model

Beginner
70 XP
25 min
Lesson Content

The CSS Box Model

Every HTML element is a rectangular box. The CSS box model describes how these boxes are sized and spaced. It consists of four parts: content, padding, border, and margin.

Box Model Components

  • Content: The actual content (text, images, etc.)
  • Padding: Space inside the element, between content and border
  • Border: A line around the padding
  • Margin: Space outside the element, between border and other elements

Visual Representation

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ† Margin (outside)
โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚
โ”‚ โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ โ”‚ โ† Border
โ”‚ โ”‚ โ”‚   โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ โ”‚ โ”‚
โ”‚ โ”‚ โ”‚   โ”‚  Content  โ”‚ โ”‚ โ”‚ โ”‚ โ† Padding
โ”‚ โ”‚ โ”‚   โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ”‚ โ”‚
โ”‚ โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ”‚
โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Example

.box {
  width: 200px;
  padding: 20px;
  border: 2px solid #ccc;
  margin: 10px;
}
Example Code

Create a box with padding, border, and margin

<!DOCTYPE html>
<html><head><style>
.box {
  width: 200px;
  padding: 20px;
  border: 2px solid #3b82f6;
  margin: 15px;
  background: #eff6ff;
}
</style></head><body>
<div class="box">Box model demo</div>
</body></html>

Expected Output:

Box model demo
Study Tips
  • โ€ขRead the theory content thoroughly before practicing
  • โ€ขReview the example code to understand key concepts
  • โ€ขProceed to the Practice tab when you're ready to code