Sub topic 2
Margin: Space Outside the Border
Prerequisites: basic HTML structure, CSS selectors and declarations, and common length units such as px, rem, and %. This chapter focuses on how spacing and sizing affect layout.
Margin: Space Outside the Border
A margin is space outside an element's border. It separates the element from neighbouring elements. Margin is transparent, so the element's background does not fill it.
Margins can use one, two, three, or four values:
.card {
margin: 10px 20px 30px 40px; /* top right bottom left */
padding: 8px 16px; /* vertical horizontal */
}Adjacent vertical margins between block elements can collapse. The larger margin usually becomes the gap:
h2 { margin-bottom: 24px; }
p { margin-top: 16px; }The gap is 24px, not 40px. Horizontal margins do not collapse.
`box-sizing`: Content Box Versus Border Box
With the default content-box, width sets only the content width. Padding and borders are added outside it. A 300px width with 40px padding and 10px of borders produces a 350px border box.
.card {
width: 300px;
padding: 20px;
border: 5px solid #333;
margin: 10px;
}With border-box, the declared width includes content, padding, and border. The same card remains 300px wide, and its content area becomes 250px.
*,
*::before,
*::after {
box-sizing: border-box;
}Inspecting Boxes in Developer Tools
Select an element in browser developer tools and open the Computed or Layout panel. The box-model diagram shows content, padding, border, and margin. Hovering over a layer highlights that region on the page.
When an element is unexpectedly wide, check box-sizing, padding, borders, and margins separately. Also check whether the browser's user-agent stylesheet added default margins to headings or paragraphs.
How Display Type Changes Box Behaviour
| Display type | Width and height | Typical spacing behaviour |
|---|---|---|
| `block` | Apply; width defaults to available space | Starts on a new line |
| `inline` | Width and height do not apply normally | Flows within text |
| `inline-block` | Width and height apply | Flows inline but behaves like a box |
Exercise
A content-box element has width: 200px, padding: 10px on both sides, and border: 2px on both sides. What is its border-box width?
Show answer
224px: 200 + 20px of padding + 4px of border.