๐Ÿ“ฆ CSS

The CSS Box Model & Margin Collapse โ€” The Bug You've Definitely Hit

๐Ÿ“… Jul 3, 2026 โฑ 3 min read

"Why is there a gap here?" and "why is my width wrong?" โ€” both answered by the box model and its weirdest rule.

border-box: the universal fix

*, *::before, *::after { box-sizing: border-box; }
/* width: 300px now INCLUDES padding + border.
   Without it: 300px content + 32px padding + 4px border = 336px surprise */

Margin collapse โ€” the famous gotcha

Vertical margins of adjacent/parent-child blocks MERGE into the larger one (they don't add). Three symptoms:

The fixes

/* any of these stop parent-child collapse: */
.parent { padding-top: 1px; }          /* or border */
.parent { display: flow-root; }        /* cleanest */
.parent { display: flex; flex-direction: column; }  /* flex/grid never collapse */
/* modern habit: use gap in flex/grid instead of margins between siblings */

Bonus: outline draws OUTSIDE the box without affecting layout (focus rings); border takes space. Full lesson: Box Model.

โ† All Articles