The box model
🏠The everyday picture
A framed photo on a wall: the photo, the white mount around it, the frame, and the empty wall space before the next frame. Every element on a web page is a box built the same way.
📘What it really is
- Every element is a rectangular box with four layers, from the inside out:
- content: the text or image;
- padding: space inside the edge (the mount);
- border: the edge itself (the frame);
-
margin: space outside, separating it from neighbours (the wall).
-
By default,
widthsets only the content, so padding and border are added: a 300px box with 20px padding and a 2px border is really 344px wide. This surprises everyone. -
The fix almost every site uses, at the top of the stylesheet:
*, *::before, *::after {
box-sizing: border-box;
}
Now width includes padding and border, so 300px means 300px.
-
Block elements (
div,p,h1,section) start on a new line and stretch full width. Inline elements (a,strong,span) sit inside a line of text and ignore width and height. -
Vertical margins between two blocks can merge ("collapse"): 20px below one and 30px above the next gives 30px, not 50px.
🖱️Try it
Add the box-sizing rule to the top of style.css. Then Inspect any element: at the bottom of the Styles panel
(or in the Computed tab) is a diagram of its content, padding, border and margin. Hover each layer to see it
highlighted on the page.
✅Quick check
A box is width: 200px with 10px padding and a 1px border, without border-box. How wide is it?
Show the answer
222px: 200 + 10 + 10 + 1 + 1.
Why can't you set a width on a link (<a>) without changing anything else?
Show the answer
Links are inline elements, which ignore width. Make it display: inline-block or block.
