HTML and CSS · Lesson 6 of 12
The box model
Every element is a box: the content, then padding, then a border, then margin outside it. Most "why is this the wrong size?" bugs are box-model bugs.
Content, padding, border, margin
Padding is space inside the border; the background shows through it. Margin is space outside the border, between this box and others. By default, width sets only the content: a box with width: 200px; padding: 20px; border: 5px is actually 250 px wide.
That's why almost every site starts with *, *::before, *::after { box-sizing: border-box; }: then width includes the padding and border, and 200px means 200px.
Margin collapsing
Vertical margins between blocks collapse: a 30px bottom margin above a 20px top margin gives a 30px gap, not 50px. It doesn't happen inside flex or grid containers, or with padding, which is one reason layouts often use gap instead of margins.
Your turn
Make a card that is exactly 300px wide in total, with 16px of padding, a 2px border and rounded corners, and 24px of space below it.
Show a solution
<style>
.card {
box-sizing: border-box;
width: 300px;
padding: 16px;
border: 2px solid #ced4da;
border-radius: 12px;
margin-bottom: 24px;
}
</style>
<div class="card">I'm a card</div>
<div class="card">Me too</div>In the interview
Explain the CSS box model.
Each element is a box with content, padding, border and margin, from the inside out. With the default box-sizing: content-box, width is only the content; with border-box, width includes padding and border.
What is margin collapsing?
Adjacent vertical margins of block elements combine into the larger of the two instead of adding up. It doesn't happen in flex or grid layouts, or when padding or a border separates the margins.
Padding or margin for space?
Padding is inside the box (the background and the clickable area grow); margin is outside, between boxes. Spacing between items in a flex or grid layout is usually best done with gap.