HTML & CSSEasy
What is the box model?
The CSS box model describes every element as a rectangular box made of four layers: the content, padding around it, a border, and margin outside the border. The box-sizing property decides whether width and height measure only the content (content-box, the default) or include padding and border (border-box).
The layers (inside out)
- Content: text, images and child elements; sized by
width/height. - Padding: space inside the border; takes the element's background.
- Border: the visible edge.
- Margin: transparent space outside, separating the box from neighbors.
box-sizing makes the math easier
content-box(default):width: 200px; padding: 20px; border: 2pxrenders 244px wide.border-box: the same element is exactly 200px; padding and border are taken from inside.
Most projects apply this globally:
*, *::before, *::after { box-sizing: border-box; }
Margin behaviors to know
- Margin collapsing: adjacent vertical margins of block elements merge into the larger value (20px + 30px = 30px, not 50px). It does not happen in flex or grid containers.
margin: autocenters a block horizontally when it has a width.- Margins can be negative.
Inspecting it
DevTools shows the box model diagram for any element, which is the fastest way to debug unexpected spacing.
Interview tip
Calculate a content-box width out loud; it shows you truly understand the model.
Code example
html
1<style>2 body { font-family: system-ui; }3 .box {4 width: 200px;5 padding: 20px;6 border: 4px solid #0b1020;7 margin: 16px 0;8 background: #dbeafe;9 }10 .content { box-sizing: content-box; }11 .border { box-sizing: border-box; background: #fef9c3; }12 /* Margin collapsing: the gap between these two is 30px, not 50px */13 .a { margin-bottom: 20px; }14 .b { margin-top: 30px; }15</style>16<div class="box content" id="c">content-box</div>17<div class="box border" id="b">border-box</div>18<p class="a">Paragraph A (margin-bottom 20px)</p>19<p class="b">Paragraph B (margin-top 30px)</p>20<pre id="out"></pre>21<script>22 const w = (id) => document.getElementById(id).getBoundingClientRect().width;23 document.getElementById("out").textContent =24 `content-box rendered width: ${w("c")}px\nborder-box rendered width: ${w("b")}px`;25</script>
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the HTML & CSS set.