CSS Box Model — Why width: 100% Adds 64px Overflow
A button with width: 100% and padding rendered 64px wider than its container.
20+ years shipping production JavaScript and front-end systems at scale. Written from production experience, not tutorials.
- ✓Basic programming fundamentals
- ✓A computer with internet access
- ✓Willingness to follow along with examples
- The box model: every element is a rectangular box with content, padding, border, margin
- Default box-sizing is content-box: declared width excludes padding and border
- Border-box includes padding and border in width — the production standard
- Margin is outside (transparent), padding inside (background fills it)
- Vertical margins collapse to the larger value; horizontal margins never collapse
- Browser DevTools Computed tab shows the real box model in 2 seconds
Imagine every element on a webpage is a framed photo hanging on a wall. The photo itself is the content. The white space between the photo and the frame is the padding. The frame itself is the border. And the gap between this frame and the next one on the wall is the margin. CSS is simply the set of instructions you give the browser to style each of those framed photos — their size, colour, font, and spacing. Once you see it that way, CSS stops feeling random and starts feeling logical.
| Chrome | Firefox | Safari | Edge |
|---|---|---|---|
| ✓ | ✓ | ✓ | ✓ |
Every website you've ever visited — from Google's homepage to your favourite online shop — is built on three technologies working together: HTML for structure, JavaScript for behaviour, and CSS for visual appearance. CSS is what separates a wall of plain black text from a polished, professional interface. Without it, the web would look like a 1994 university library page. Understanding CSS isn't optional for anyone building for the web; it's the difference between shipping something people trust and something they immediately close.
The single biggest source of confusion for CSS beginners is spacing. Why is my button too big? Why is there a mysterious gap under my image? Why did adding a border break my layout? Almost every one of those questions has the same answer: you don't fully understand the CSS Box Model yet. The box model is the rulebook the browser uses to calculate how much space every element takes up on screen. Master it, and layout clicks into place.
By the end of this article you'll be able to write real CSS that styles text, sets colours and backgrounds, controls spacing with margin and padding, adds borders, and — most importantly — predict exactly how much space an element will occupy before you even open the browser. You'll also know the one property that most tutorials forget to mention, which trips up even experienced developers.
What CSS Actually Is — Selectors, Properties and Values
CSS stands for Cascading Style Sheets. Don't worry about the 'cascading' part yet — we'll get there. For now, think of CSS as a list of rules. Each rule says: 'Find these elements on the page, and make them look like this.'
Every CSS rule has three parts. A selector tells the browser which element to target. A property tells it what aspect to change (colour, size, font, etc). And a value tells it what to change it to. The syntax looks like this: selector { property: value; }. That's the entire grammar of CSS in one line.
You can write CSS in three places: directly in an HTML tag using the style attribute (called inline styles), inside a style tag in your HTML file (called internal styles), or in a completely separate .css file linked to your HTML (called external styles). For anything beyond a quick experiment, always use an external file. It keeps your HTML readable and lets you reuse styles across multiple pages without copying and pasting.
Selectors are how you aim. The three you'll use every day are the element selector (targets all tags of a type, like p or h1), the class selector (targets any element with a matching class attribute, written with a dot like .card), and the ID selector (targets one unique element, written with a hash like #main-header). Classes are the workhorse — use them constantly. IDs are for one-off unique elements.
The CSS Box Model — The Four Layers Every Element Has
Here's the mental model that changes everything. Every single element on a webpage — a paragraph, a button, an image, a div — is a rectangular box. Even if it looks round or irregular, the browser is still treating it as a rectangle underneath. And every one of those boxes is built from four nested layers.
The innermost layer is the content — your actual text, image, or whatever is inside the element. Wrapping around the content is the padding — transparent space inside the element, between the content and the border. Think of it as interior cushioning. Next comes the border — an optionally visible line around the element. Finally, on the outside, is the margin — transparent space between this element and everything around it.
Here's the critical part that confuses almost everyone. By default, when you set width: 200px on an element, you're only setting the width of the content area. The browser then adds padding and border on top of that. So if you set width: 200px, padding: 20px and border: 5px, the element actually takes up 250px (200 + 20 left + 20 right + 5 left + 5 right). That unexpected size jump is the #1 source of broken layouts for beginners.
The fix is one line of CSS that every professional stylesheet starts with. We'll cover it in the code example below — and once you understand why it works, you'll never forget it.
Margin vs Padding — Knowing Which One to Use When
Margin and padding both create space, so beginners often swap them and wonder why things look slightly off. Here's a clear rule: padding is space inside the element; margin is space outside the element. The practical difference matters more than you'd think.
Background colour and border stop at the edge of padding. They don't extend into margin. So if your element has a background colour and you want the colour to extend further into the space around your text, you need more padding. If you want empty air between two separate elements, you need margin.
There's also a quirk called margin collapse that only affects top and bottom margins (never left/right). When two vertically stacked elements both have vertical margins, the browser doesn't add them together — it uses whichever is larger. So if one element has margin-bottom: 30px and the next has margin-top: 20px, the actual gap between them is 30px, not 50px. This is intentional (it makes typography spacing consistent) but it confuses everyone the first time they encounter it.
A practical rule for deciding which to use: if you're adding space between an element and its neighbours, use margin. If you're adding breathing room between an element's edge and its own content, use padding. Think of a button: the text-to-edge gap is padding, the gap between the button and other buttons is margin.
Debugging Box Model Issues in the Browser DevTools
The browser's Developer Tools are your best friend for diagnosing box model problems. No guessing, no trial-and-error. The Computed tab shows you exactly what the browser is using for every layer of the box.
Open DevTools (F12 on Windows/Linux, Cmd+Option+I on Mac), select an element, and go to the Computed tab. You'll see a visual diagram of the box model: content, padding, border, margin — all with exact pixel values. Hover over each section to see the dimensions breakdown.
Here's a common workflow: you notice an element is wider than you intended. Open Computed, look at the width value. If it's bigger than your CSS width, the extra is coming from padding or border being added on top. The solution is either to reduce padding/border or add box-sizing: border-box. The DevTools also show you which CSS rule sets each property — so you can trace it back to the source file and line number.
Another powerful trick: use the :hov button in the Styles panel to force element states like :hover or :focus. This lets you debug interactive states without having to keep hovering. Also use the 'Toggle Element State' feature to see how padding or margins change on hover.
Putting It All Together — A Real Styled Web Card
The best way to cement CSS basics and the box model is to build something real from scratch. No contrived examples — let's style an actual profile card you could drop into a real project today.
The HTML gives us the structure: a container div with a profile image, a name, a job title, and a short bio. The CSS then layers on typography, colour, spacing, and a subtle shadow using everything we've covered. Read each comment in the code carefully — there's intentional teaching in every property choice.
Pay attention to how margin: 0 auto centres the card horizontally. This works on block elements with a defined width. The auto value tells the browser to distribute remaining horizontal space equally on both sides — which centres the element. It's one of those CSS tricks that's been around since the early 2000s and still works perfectly today.
Also notice the use of a box-shadow. It isn't part of the box model — it doesn't affect layout at all. Box shadows are purely decorative and are drawn outside the element without changing its size or pushing anything around. That makes them safe to add to any element without worrying about breaking your layout.
The Box-Sizing Trap – Why Your Layout Breaks at 3 AM
You set a width of 400px, but the element spills out to 450px. That's box-sizing: content-box biting you. By default, CSS adds padding and border on top of your declared width. So width: 400px with 20px padding and 5px border? You get a real rendered width of 450px. The fix: box-sizing: border-box tells the browser to include padding and border inside the defined width. Now 400px means 400px no matter what padding you add. This single property change stops dozens of layout bugs. Apply it globally with the universal selector at the top of every stylesheet.
Margin Collapse – The Silent Spacing Killer
Two stacked divs each with margin-bottom: 30px. You expect 60px gap. You get 30px. That's margin collapse: adjacent vertical margins combine into the larger value. It's not a bug — it's the CSS spec. But it will break your layout at 2 AM when you're shipping a feature. The mechanics: only vertical margins collapse (top/bottom), not horizontal. Only block-level elements collapse. Inline blocks, floats, and absolutely positioned elements don't collapse. To prevent it: use padding on the parent instead of margin on children, or add display: flow-root to the parent to create a new block formatting context.
The Mystery 20px Overflow That Broke a Checkout Page
- Always include box-sizing: border-box as a global reset in every project
- Never assume width means total width — check box-sizing first
- When an element overflows, the computed tab in DevTools confirms the box model instantly
Right-click element → Inspect → Computed tab (or press F12, then Ctrl+Shift+E in Firefox)Check if box-sizing is content-box or border-box. Look for padding adding to width* { box-sizing: border-box; } to CSS. Change width to max-width if parent constraint is the real issue| File | Command / Code | Purpose |
|---|---|---|
| styles.css | /* ── Element selector ───────────────────────────────────────────────────── | What CSS Actually Is |
| box-model-demo.css | /* ── THE FIX: Apply this at the top of every stylesheet you ever write ──── | The CSS Box Model |
| margin-vs-padding.css | /* ── Demonstrating the visual difference between margin and padding ────── */ | Margin vs Padding |
| debugging-devtools.css | /* No code for this section — it's about using DevTools. | Debugging Box Model Issues in the Browser DevTools |
| profile-card.html | Putting It All Together | |
| BoxSizingReset.js | const style = document.createElement('style'); | The Box-Sizing Trap – Why Your Layout Breaks at 3 AM |
| MarginCollapseFix.js | const parent = document.createElement('div'); | Margin Collapse – The Silent Spacing Killer |
Key takeaways
Interview Questions on This Topic
Can you explain the CSS box model and describe what each layer — content, padding, border and margin — actually does? How does box-sizing: border-box change the calculation?
Frequently Asked Questions
20+ years shipping production JavaScript and front-end systems at scale. Written from production experience, not tutorials.
That's HTML & CSS. Mark it forged?
6 min read · try the examples if you haven't