Sub topic 6
Control spacing with the box model
This chapter explains how the browser sizes every element and how to control the space inside and around it. It assumes you can write a basic HTML page and link a stylesheet. You should also know how a CSS rule is built from a selector, a property and a value. Units such as px and rem should be familiar, but they are explained briefly below.
Every element is a box
The browser draws each element as a rectangular box. A box has four layers, from the inside out:
- Content holds the text, image or child elements.
- Padding is the space between the content and the border. It shows the element's background color.
- Border is a line around the padding. It can have width, style and color.
- Margin is the space outside the border. It separates the box from its neighbors and is always transparent.
You can see these layers in your browser. Open the developer tools (usually F12), pick the Elements or Inspector panel and select an element. A colored diagram shows its content, padding, border and margin sizes. Use it whenever spacing looks wrong, because it shows where the extra space comes from.
How the width of a box is calculated
The width property has a surprising default. Browsers use box-sizing: content-box, so width sets only the content area. Padding and border are added on top. The border-box value makes width cover content, padding and border together.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Box sizing demo</title>
<style>
.box {
width: 300px;
padding: 20px;
border: 5px solid #1f2933;
margin-bottom: 1rem;
background: #e8f0fa;
}
.content-box { box-sizing: content-box; }
.border-box { box-sizing: border-box; }
</style>
</head>
<body>
<div class="box content-box">content-box: 350px wide in total</div>
<div class="box border-box">border-box: 300px wide in total</div>
</body>
</html>Both boxes declare width: 300px. The first renders 350px wide, because 300 + 20 + 20 + 5 + 5 = 350. The second renders 300px wide, and its content area shrinks to 250px.
With content-box, you must subtract padding and border from every width you plan. With border-box, the number you write is the space the box occupies. Most stylesheets switch to border-box for every element:
*,
*::before,
*::after {
box-sizing: border-box;
}Put this rule at the top of your stylesheet. The ::before and ::after selectors cover the pseudo-elements, which are boxes the browser can generate before or after an element's content.
Padding, border and margin in practice
Each layer has one property for all sides and one for each side. The shorthand takes values in a fixed order.
| Shorthand | Meaning |
|---|---|
| `padding: 1rem` | All four sides are 1rem |
| `padding: 1rem 2rem` | Top and bottom 1rem, left and right 2rem |
| `padding: 1rem 2rem 3rem` | Top 1rem, left and right 2rem, bottom 3rem |
| `padding: 1rem 2rem 3rem 4rem` | Top, right, bottom, left (clockwise) |
| `padding-inline: 2rem` | Left and right in left-to-right text |
| `margin: 0 auto` | No vertical margin, left and right share the free space |
The margin property follows the same patterns. Padding cannot be negative, but margin can, which pulls a box toward or over its neighbor. Use negative margins rarely, since they make layouts hard to predict.
The border shorthand takes a width, a style and a color, such as border: 1px solid #d0d7de. If you leave out the style, no border appears, because the default style is none. This is a common reason for a border that seems to be ignored.
For sizes, prefer rem over px for spacing. One rem equals the root font size, normally 16px. Spacing then grows when a visitor raises their browser's default text size. Percentage padding and margin are measured against the width of the containing block, even for top and bottom values.
Centering a column
The spine's page uses a centered reading column:
main {
max-width: 60rem;
margin: 0 auto;
padding: 2rem 1rem;
}The max-width stops the column from growing past 60rem on a wide screen. On a narrow screen the column shrinks with the window, so it adapts without a media query. The margin: 0 auto rule works because main is a block element with a limited width. The browser splits the leftover horizontal space equally between the left and right margins. Auto margins do nothing for height, so margin: auto will not center an element vertically in this layout.
Margin collapsing
Vertical margins between block siblings do not add up. When one box's bottom margin touches the next box's top margin, the browser keeps only the larger one. This is called margin collapsing.
h2 {
margin: 0 0 2rem;
}
p {
margin: 1rem 0 0;
}An h2 followed by a p has 2rem between them, not 3rem. Collapsing also applies between a parent and its first or last child when nothing separates their margins, such as padding or a border. The child's margin can then appear to push the parent away from its neighbors.
Several rules do not collapse. Horizontal margins never collapse, and neither do margins on flex or grid items. Margins also stay separate when a parent has padding or a border, or when it creates its own formatting context, for example with display: flow-root.
A reliable habit avoids most surprises. Space elements in one direction only, usually with margin-top or margin-bottom on the elements that need it, rather than setting both. In flex and grid containers, use the gap property, which you will meet in the layout chapters.
Block and inline boxes
The display value decides how a box behaves in the flow of the page.
- Block boxes start on a new line and stretch across their parent. Examples are
div,p,sectionandh1. - Inline boxes sit within a line of text. Examples are
a,spanandstrong. Theirwidthandheightare ignored, and vertical margins have no effect. Vertical padding and borders draw, but they do not push the surrounding lines away. - Inline-block boxes sit in a line like inline boxes but accept width, height and all margins and padding.
If an a element needs a bigger clickable area, make it display: inline-block before you add vertical padding. Larger targets also help touch and keyboard users.
nav a {
display: inline-block;
padding: 0.5rem 0.75rem;
}Applying it to the personal site
Combine these ideas for the project cards and sections:
*,
*::before,
*::after {
box-sizing: border-box;
}
body {
margin: 0;
}
main {
max-width: 60rem;
margin: 0 auto;
padding: 2rem 1rem;
}
section + section {
margin-top: 3rem;
}
.project-card {
padding: 1rem;
border: 1px solid #d0d7de;
border-radius: 0.5rem;
}The body rule removes the browser's default 8px margin, which would otherwise leave a gap around the page. The section + section selector is an adjacent sibling selector. It matches a section that directly follows another section, so the first section gets no extra space above it. The border-radius property rounds the corners of the border box.
Common errors
- Horizontal scrolling on small screens. A fixed
widthplus padding undercontent-boxexceeds its parent. Apply theborder-boxreset and prefermax-widthoverwidthfor containers. - A border that does not show. The
border-styleis missing. Write1px solid, not only a width and color. - Vertical margin that does nothing. The element is inline. Change its
display, or use padding on the parent. - Spacing smaller than expected. Adjacent vertical margins collapsed. Use one direction of margin or a
gap. - Centering that fails.
margin: 0 autoneeds a block element with a width ormax-widthsmaller than its parent.
Exercise
A div has box-sizing: content-box, width: 200px, padding: 10px 20px, border: 2px solid black and margin: 15px. How wide is the visible box (content, padding and border), and how much horizontal space does it take up on the page including its margins? How do those numbers change under border-box?
Show answer
Under content-box, the visible width is 200 + 20 + 20 + 2 + 2 = 244px. With the 15px margins on each side, it takes 244 + 15 + 15 = 274px of horizontal space. Under border-box, the visible width is exactly 200px (the content area shrinks to 200 - 40 - 4 = 156px), and the horizontal space taken including margins is 230px.
Exercise
An h2 has margin-bottom: 2rem. The p after it has margin-top: 1.5rem. Both are block siblings with no padding or border between them. What is the vertical gap between them, and why?
Show answer
The gap is 2rem. The two vertical margins touch, so they collapse and the browser keeps the larger value instead of adding them to 3.5rem.