Box Model, Margin and Padding
What Is It?
Every element generates boxes. The box model separates content, padding inside the border, the border itself, and margin outside it.
Properties, Tags and Attributes Explained
padding: Space between content and border.border: A line around the padding and content.margin: Space outside the border; adjacent vertical block margins can collapse.box-sizing: border-box: Includes padding and border in the declared width and height.
Each example is a complete HTML page. The CSS is inside the head's style element. Use Try in new tab to edit the CSS or HTML, run your changes, and reset the example.
Example 1: See the layers
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Box Model, Margin and Padding</title>
<style>
.box { padding: 20px; border: 4px solid #2563eb; margin: 20px; background: #dbeafe; }
</style>
</head>
<body>
<div class="box">Content inside padding and a border</div><p>Another element outside the box</p>
</body>
</html>What you see: The blue fill includes padding; margin separates the box from nearby content.
Example 2: Predictable width
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Box Model, Margin and Padding</title>
<style>
.box { box-sizing: border-box; width: 240px; padding: 20px; border: 4px solid #15803d; background: #dcfce7; }
</style>
</head>
<body>
<div class="box">Total border-box width: 240px</div>
</body>
</html>What you see: The content width is 192px: 240 minus 40px padding and 8px border.
When and Where to Use It
Use padding to give a button breathing room, margin to separate components, and border-box for predictable sizing.
Common Mistake or Useful Tip
Margin can be negative; padding cannot. Use gap for consistent spacing in Flexbox and Grid.
Try It Yourself
Increase padding to 30px in example 2 and observe that the outer width stays fixed.