The CSS Box Model is the foundational layout concept in CSS. Every HTML element on a web page is rendered inside a rectangular box composed of four layered areas: Content, Padding, Border, and Margin.
The total visual dimensions of an element depend on how browser layout engines calculate box layer dimensions:
.box {
width: 300px;
padding: 20px;
border: 5px solid #38bdf8;
margin: 15px;
box-sizing: border-box; /* Includes padding & border inside width */
}
The 4 Box Model layers explained from inside to outside:
flowchart TD
A["MARGIN (Outer Spacing Layer)"] --> B["BORDER (Outline Boundary Layer)"]
B --> C["PADDING (Inner Spacing Layer)"]
C --> D["CONTENT (Text / Images / Children)"]
content-box vs border-boxBy default, CSS uses box-sizing: content-box, where padding and borders add extra width to the declared width. Modern web development uses box-sizing: border-box so declared width includes padding and border:
/* Universal reset for modern box model sizing */
*, *::before, *::after {
box-sizing: border-box;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS Box Model Demonstration</title>
<style>
*, *::before, *::after {
box-sizing: border-box;
}
.box-demo {
width: 100%;
max-width: 400px;
padding: 24px;
border: 4px solid #38bdf8;
margin: 20px auto;
background-color: #1e293b;
border-radius: 8px;
}
</style>
</head>
<body style="background-color: #0f172a; color: #f8fafc; font-family: system-ui, sans-serif; padding: 2rem;">
<div class="box-demo">
<h3 style="margin-top: 0; color: #38bdf8;">Border-Box Calculation</h3>
<p>With <code>box-sizing: border-box</code>, the padding and border are included in the max-width!</p>
</div>
</body>
</html>
box-sizing: border-box globally: Use a universal CSS reset (* { box-sizing: border-box; }) so element widths remain predictable across all layout designs.Write a universal CSS reset rule applying box-sizing: border-box to all elements (*, *::before, *::after)!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.