Free Online Code Editor
Understand content, padding, border, and margin in CSS.
<!DOCTYPE html>
<html>
<head>
<title>CSS Box Model</title>
<style>
body { font-family: Arial, sans-serif; padding: 20px; }
.box {
width: 200px;
padding: 20px;
border: 5px solid #3b82f6;
margin: 20px;
background: #dbeafe;
}
/* Default box-sizing: content-box */
.content-box {
box-sizing: content-box;
/* Total width = 200 + 40 + 10 + 40 = 290px */
}
/* Border-box includes padding and border in width */
.border-box {
box-sizing: border-box;
/* Total width = 200px (includes padding and border) */
}
/* Margin collapsing */
.margin-test {
margin-top: 30px;
margin-bottom: 30px;
background: #fbbf24;
padding: 10px;
}
/* Auto margins for centering */
.centered {
width: 300px;
margin: 0 auto;
background: #10b981;
color: white;
padding: 20px;
text-align: center;
}
</style>
</head>
<body>
<h1>CSS Box Model Demo</h1>
<h2>Content-Box (Default)</h2>
<div class="box content-box">
Width: 200px + padding + border
</div>
<h2>Border-Box</h2>
<div class="box border-box">
Width: 200px (includes padding & border)
</div>
<h2>Margin Collapsing</h2>
<div class="margin-test">First box (30px bottom margin)</div>
<div class="margin-test">Second box (30px top margin)</div>
<p>Note: Margins collapse to 30px, not 60px!</p>
<h2>Centering with Auto Margins</h2>
<div class="centered">I am centered!</div>
</body>
</html>The box model consists of content, padding, border, and margin. box-sizing: content-box (default) adds padding/border to width. box-sizing: border-box includes them in the width. Margins can collapse vertically.