Sub topic 5
Margin: space outside the border
This chapter assumes you can write CSS rules with selectors and declarations, and that you know the units px, em, rem, and %. It also assumes you know the four layers of the box (content, padding, border, margin) from the overview chapter. Here we look closely at the outermost layer.
What margin is
Margin is the space CSS reserves around the outside of an element's border. It does not belong to the element's visible surface. It is the gap between this box and its neighbours, or between this box and the edge of its container.
Three facts follow from that definition:
- Margin is always transparent. The element's
backgroundpaints under the content and padding, and it extends to the border edge (by default, under the border too). It never paints into the margin. - Margin is not part of the element's clickable or hoverable area. A click in the margin hits whatever is behind it, often the parent.
- Margin is not included in
widthorheight, whicheverbox-sizingvalue you use. Neithercontent-boxnorborder-boxever counts margin.
Margin properties and shorthand
Each side has its own longhand property: margin-top, margin-right, margin-bottom, and margin-left. The margin shorthand sets several sides at once. The number of values decides which sides they apply to.
| Values | Meaning | Example | Result |
|---|---|---|---|
| 1 | All four sides | `margin: 10px` | 10px on every side |
| 2 | Vertical, then horizontal | `margin: 10px 20px` | 10px top and bottom, 20px left and right |
| 3 | Top, horizontal, bottom | `margin: 10px 20px 30px` | 10px top, 20px left and right, 30px bottom |
| 4 | Top, right, bottom, left (clockwise) | `margin: 10px 20px 30px 40px` | Each side set separately |
/* top right bottom left */
.box {
margin: 10px 20px 30px 40px;
padding: 8px 16px;
}A common mistake is writing margin: 0 auto 20px and forgetting that three values mean top, horizontal, bottom. If a side gets the wrong value, count the values and check this table.
The shorthand always resets every side. Writing margin: 20px after margin-left: 40px in the same rule discards the 40px. If you want to change only one side, use the longhand property, and put it after the shorthand.
How margin adds to the space an element takes
Margin matters when you calculate how much room an element occupies. Take the card from the earlier chapters, with the default box-sizing: content-box:
.card {
width: 300px;
padding: 20px;
border: 5px solid #333;
margin: 10px;
}The horizontal arithmetic is:
- Content width: 300px.
- Add padding on both sides: 300 + 40 = 340px.
- Add border on both sides: 340 + 10 = 350px. This is the border box width.
- Add margin on both sides: 350 + 20 = 370px of horizontal space.
The element looks 350px wide, but it uses 370px in the layout. The same method works vertically with height and the top and bottom values. When the box has box-sizing: border-box, step 1 changes (the 300px already includes padding and border), but step 4 stays the same. Margin is always added on top.
Auto margins and centring
The value auto lets the browser compute the margin from the space left over. It is the standard way to centre a block horizontally.
<style>
.page {
width: 40rem;
max-width: 100%;
margin-left: auto;
margin-right: auto;
background: #eef;
}
</style>
<div class="page">This block is centred in its parent.</div>The browser takes the parent's width, subtracts the element's own width (including padding and border), and splits the remainder between the two auto margins. Centring fails in three common situations:
- The element has no explicit width. A block with
width: autoalready fills its parent, so the leftover space is zero and there is nothing to share. Set awidthormax-widthfirst. - The element is inline. Inline boxes ignore
width, andautomargins do not centre them. Usetext-align: centeron the parent, or change the element'sdisplay. - You used
margin: autoand expected vertical centring. In normal block layout, anautotop or bottom margin computes to0. Vertical centring this way works only in layouts such as flexbox and grid, whereautomargins absorb free space in both directions.
In a flex container, an auto margin takes up all the free space on its side. That makes margin-left: auto a convenient way to push one item to the far end of a row.
Negative margins
Margins can be negative. A negative value pulls the element toward (or past) the neighbour or container edge instead of pushing it away.
.pull-out {
margin-left: -16px; /* shifts the box 16px to the left of where it would sit */
}
.overlap-next {
margin-bottom: -8px; /* the next sibling starts 8px higher */
}Negative margins do not change the element's own size, with one exception. A negative margin-right on a block with width: auto makes the block wider, because the browser needs the content box plus margins to fill the container exactly. Use negative margins sparingly. They create overlaps that are hard to follow, and they interact with margin collapsing, covered in a later chapter.
Percentage margins
A percentage margin is calculated against the width of the containing block, which is usually the parent's content width. This applies to all four sides, including margin-top and margin-bottom.
.parent {
width: 600px;
}
.parent > .child {
margin-top: 10%; /* 10% of 600px = 60px, not 10% of the parent's height */
}The rule is a frequent source of surprise. A child with margin-top: 10% inside a 600px-wide, 200px-tall parent gets a 60px top margin. The parent's height plays no part. The rule exists so that widths and heights never depend on each other circularly, but it means percentage vertical spacing scales with the width of the layout.
How display type affects margins
Display type decides which margins take effect:
- Block boxes respect margins on all four sides.
- Inline boxes (such as
<span>and<a>) respectmargin-leftandmargin-right. Theirmargin-topandmargin-bottomhave no effect on layout, so the line height does not change. - Inline-block boxes respect all four margins. Vertical margins increase the height of the line they sit on.
Because inline-block elements sit on a line, whitespace between them in the HTML creates a gap of roughly one space character. Developers often mistake this gap for margin. If you see an unexplained gap of 4 to 5px between inline-block elements, check the whitespace in the markup before you adjust the margins.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `margin: 0 auto` does not centre | No `width` set, or the element is inline | Give the element a `width` or `max-width`, and use `display: block` |
| Vertical margin on a `<span>` does nothing | Inline boxes ignore vertical margin | Use `display: inline-block` or `display: block` |
| The gap between two stacked blocks is smaller than the two margins added together | Adjoining vertical margins collapse | See the margin collapsing chapter |
| Spacing doubles between siblings | Both siblings have margin on the shared edge | Put spacing on one side only, for example `margin-bottom` on every item |
| A later `margin-left` is overridden | A later `margin` shorthand resets all sides | Put longhands after the shorthand |
| Percentage spacing looks wrong | The percentage is based on width | Use `rem` or `px`, or accept width-based scaling |
A reliable habit is to give each element margin on a single axis side, for example only margin-bottom for vertical rhythm in a stack. It keeps the spacing predictable and reduces surprises when elements are reordered.
Summary of rules
- Margin sits outside the border, is always transparent, and is not part of the element's
widthorheight. - The shorthand takes one to four values, and the longhand properties apply only to a single side.
autohorizontal margins centre a block that has a defined width.autovertical margins are0in normal block layout.- Percentages refer to the containing block's width, on every side.
- Inline boxes ignore vertical margins. Block and inline-block boxes respect all four.
Exercise
An element has width: 200px; padding: 10px 15px; border: 4px solid; margin: 12px 20px; and the default box-sizing. Its parent is 800px wide and 300px tall. (a) How much horizontal space does the element occupy? (b) If you add margin-top: 5%, how many pixels is the top margin?
Show answer
(a) Content 200 + padding 30 (15 on each side) + border 8 (4 on each side) = 238px for the border box. Add horizontal margin 40px (20 on each side) to get 278px. (b) A percentage margin is calculated from the containing block's width, so 5% of 800px = 40px. The parent's 300px height is not used.
Exercise
A <span class="tag"> has margin: 20px; and padding: 4px 8px;. Sibling text sits on the same line. Which of its margins change the layout, and what would you change so that the vertical margin also takes effect?
Show answer
Only the left and right margins (20px each) change the layout, because an inline box ignores top and bottom margin. Setting display: inline-block (or block) makes the 20px top and bottom margins apply too.
Exercise
You write .panel { width: auto; margin: 0 auto; } and the panel is not centred. Why, and what is the smallest fix?
Show answer
With width: auto, a block fills its container, so there is no leftover space to divide between the auto margins. The smallest fix is to give the panel a narrower width, for example width: 40rem or max-width: 40rem.