CSS Box Model
The fundamental layout principle of the web where every element is represented as a rectangular box.
Detailed Explanation
The box model consists of four parts: Content, Padding, Border, and Margin. Understanding how these interact, especially the difference between `content-box` (default) and `border-box` (standard in modern dev), is essential for predictable layouts. In `border-box`, the width and height include the padding and border, preventing elements from 'growing' unexpectedly when you add styling.
Quick Summary
The CSS box model describes every element as four nested rectangles , content, padding, border, and margin , and defines how their dimensions combine to produce the element's total size on the page.
Key Takeaways
- content-box (the default) excludes padding and border from width/height; border-box includes them.
- Most modern resets set `* { box-sizing: border-box }` to make widths predictable.
- Margin collapsing between vertically adjacent block elements is the most surprising part of the model.
- Inline elements ignore vertical padding and margin for layout purposes (but still paint backgrounds).
- DevTools' computed panel visualises the four layers , it is the fastest way to debug a layout bug.
When to use it
- Building card components with consistent widths regardless of padding or border thickness.
- Designing form inputs where 100% width must include the border without overflowing the container.
- Debugging unexpected horizontal scrollbars caused by content-box widths with padding.
- Aligning grid or flex children whose total widths must add up to the parent.
Common Mistakes
- Setting width: 100% with padding and getting overflow because the default is content-box.
- Forgetting that margins collapse vertically , two 20px margins become 20px, not 40px.
- Applying margin to inline elements expecting vertical spacing , it has no effect.
- Mixing box-sizing values in a single layout and producing inconsistent sizes between siblings.
CSS Box Model, Frequently Asked
Why is border-box the modern default?
Because when designers think in widths, they include padding and borders. content-box forces extra arithmetic and is the most common cause of off-by-pixel bugs. Setting box-sizing: border-box globally eliminates that whole class of issues.
What is margin collapsing?
When two block elements are stacked vertically, the larger of their adjacent margins is used instead of the sum. It applies only to vertical margins on block-level elements outside flex/grid containers.
Does the box model apply to flex and grid items?
Yes, but margin collapsing does not. Inside a flex or grid container, margins act independently and never collapse.