CSS Box Model
CSS Box Model: How Browsers Calculate Element Dimensions
Every HTML element renders as a rectangular box built from four concentric layers: content, padding, border, and margin. Understanding the CSS Box Model explains exactly how width, height, spacing, and borders combine on screen.
flowchart TD
M["Margin (Transparent outer gap)"] --> B["Border (Visible edge around box)"]
B --> P["Padding (Inner space with background)"]
P --> C["Content (Text, image, or child elements)"]
Content-Box vs. Border-Box
Under the browser default (box-sizing: content-box), setting width: 300px; padding: 20px; border: 5px solid; produces a rendered box that is 300 + 40 + 10 = 350px wide! That extra math causes two 50% columns with padding to wrap onto separate lines.
Switching globally to box-sizing: border-box; includes both padding and border inside the declared width and height, so a 300px box stays strictly 300px wide.
*,
*::before,
*::after {
box-sizing: border-box;
}
.pricing-card {
width: 320px;
padding: 24px;
border: 2px solid #2563eb;
margin: 16px auto;
background-color: #ffffff;
border-radius: 10px;
}
Inspecting Boxes in Browser DevTools
Open DevTools in Chrome, Edge, or Firefox and inspect any element to view the interactive Box Model diagram in the Computed or Layout tab. Hovering each ring highlights exact pixel sizes for margin, border, padding, and content on the live page.
Common Mistakes to Avoid
- Forgetting
box-sizing: border-boxon::beforeand::after: Always applybox-sizing: border-boxto pseudo-elements too so decorative badges behave identically. - Confusing
marginwithpaddingon clickable cards: Margin sits outside the clickable element area and background, while padding expands the clickable target inside. - Adding borders to fixed-width flex items without
border-box: Extra border pixels break tight multi-column math.
Frequently Asked Questions
Does margin count toward an element's width under box-sizing: border-box?
No. border-box absorbs padding and border into width and height, while margin always remains outside the element's box.
Is applying * { box-sizing: border-box; } safe for production?
Yes. Nearly every modern CSS framework—including Tailwind CSS and Bootstrap—applies box-sizing: border-box globally as its very first reset rule.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.