DEV Community

Nganggur Dev
Nganggur Dev

Posted on

Mastering CSS Box Model: Margin, Padding, and Border Explained with Examples

If you’re learning CSS, one of the first things you’ll hear is: “Everything is a box.” And to control how these boxes behave, you need to understand three essential properties: margin, padding, and border.

In this beginner-friendly article, I will explain to you:

✅ What margin, padding, and border actually do
✅ How they affect layout and spacing
✅ Real examples to help you visualize the difference

📦 The Box Model Basics
Every HTML element is treated like a rectangular box. And each box has four main parts:

  • Content (text/image inside)
  • Padding — space between content and border
  • Border — the visible edge around the element = Margin — space outside the border, separating it from other elements

Example:

.box {
  margin: 20px;
  padding: 15px;
  border: 2px solid #333;
}
Enter fullscreen mode Exit fullscreen mode

This example adds space around the box, space inside the box, and a border around it. Many layout issues in CSS come from misunderstanding these properties fixing them often starts here.

👉 In my full guide, I break it all down with diagrams and code snippets:
Learn CSS for Beginners #7: Margin, Padding, and Border with Examples

Top comments (0)