Here is the idea that makes the rest of CSS click: every element on a page is a rectangular box. A heading, a link, an image, a paragraph. Boxes inside boxes.
Each box has four layers, from the inside out:
- Content: the text or image itself.
- Padding: empty space between the content and the border.
- Border: a line around the padding (it can be invisible).
- Margin: empty space outside the border, pushing other boxes away.
Think of a framed picture on a wall. The picture is the content, the mat around it is the padding, the frame is the border, and the gap between that frame and the next one on the wall is the margin.
See all four layers
<style>
.box {
width: 200px;
padding: 20px;
border: 6px solid #d94a00;
margin: 30px;
background: #fdebd9;
}
body { background: #eee; }
</style>
<div class="box">Content area</div>
<div class="box">A second box. Notice the gap between them.</div>
The tinted area is the content plus the padding. The orange line is the border. The grey gap around the boxes is the margin. Margins are always transparent: the background of the box does not fill them.
Use the browser to see it
Open the developer tools on any element and look at the Computed tab or the box diagram in the Styles panel. It shows the four layers as nested rectangles with their sizes. This is the fastest way to find out where unexpected space is coming from. See Inspecting CSS with Developer Tools.
Why it matters
- The total space a box takes is more than its
width. Padding and border are added on top, unless you changebox-sizing. - Most “why is this off by a few pixels?” and “why is there a horizontal scrollbar?” problems come back to the box model.
The next lessons cover each layer: width and height, padding, margin, and the setting that changes the maths, box-sizing.