"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:
- h2 with margin-bottom 24px + p with margin-top 16px โ gap is 24, not 40
- Child's margin-top "escapes" through the parent, pushing the PARENT down
- Empty elements' own margins collapse through them
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.