CSS Weekly

Archives
Sponsor
June 29, 2026

CSS Tip #1: Master the Box Model

CSS Tip #1: Master the Box Model

Understanding the CSS Box Model is fundamental to creating layouts that work exactly as you expect. Let's break it down!

What is the Box Model?

Every HTML element is essentially a rectangular box with four distinct areas:

  1. Content - The actual content (text, images, etc.)
  2. Padding - Space between content and border
  3. Border - The border around the element
  4. Margin - Space outside the border

Visual Representation

┌─────────────────────────────────────┐ ← Margin
│ ┌─────────────────────────────────┐ │ ← Border
│ │ ┌─────────────────────────────┐ │ │ ← Padding
│ │ │        Content Area         │ │ │
│ │ └─────────────────────────────┘ │ │
│ └─────────────────────────────────┘ │
└─────────────────────────────────────┘

Practical Example

.box {
  width: 200px;
  height: 100px;
  padding: 20px;
  border: 2px solid #333;
  margin: 10px;
  background-color: #f0f0f0;
}

Total width = 200px (content) + 40px (padding) + 4px (border) + 20px (margin) = 264px

Box-Sizing Property

The box-sizing property controls how width and height are calculated:

/* Default behavior */
.element {
  box-sizing: content-box; /* width/height = content only */
}

/* Modern approach */
.element {
  box-sizing: border-box; /* width/height = content + padding + border */
}

Pro Tip

Always use box-sizing: border-box for predictable layouts:

* {
  box-sizing: border-box;
}

This makes width calculations much more intuitive!

Common Gotchas

  1. Margin collapse - Vertical margins between adjacent elements collapse to the larger value
  2. Percentage margins - Calculated relative to the parent's width, not height
  3. Negative margins - Can pull elements outside their normal flow

Next Up

Tomorrow we'll dive into Flexbox fundamentals. Flexbox makes it easy to create flexible, responsive layouts without the complexity of floats and positioning.

Keep coding! 🚀


Have questions about the box model? Reply to this email and I'll help clarify!

← Newer CSS Tip #2: Flexbox Fundamentals Older → Welcome to CSS Weekly! 🎨

Add a comment:

Powered by Buttondown, the easiest way to start and grow your newsletter.