The margin property
margin is the outer spacing: transparent space around an element's border that pushes its neighbours away. It is a shorthand for margin-top, margin-right, margin-bottom and margin-left.
Syntax
margin: 16px; /* all four sides */
margin: 16px 24px; /* top and bottom | right and left */
margin: 8px 24px 16px; /* top | right and left | bottom */
margin: 8px 16px 24px 32px; /* top | right | bottom | left */
margin: 0 auto; /* center a block with a set width */ - Initial value
0- Inherited
- no
- Applies to
- all elements except internal table elements (rows, cells and so on)
Values
| Value | What it does |
|---|---|
<length> | a fixed distance: px, rem, em and so on; it can be negative, and then the element overlaps its neighbour |
<percentage> | a percentage of the containing block's width — even for the top and bottom margins |
auto | the browser distributes the free space: margin: 0 auto centers a block with a set width, and in a flex container auto pushes the item away |
Example
.box {
padding: 12px;
background: #e0f2fe;
border: 1px solid #0284c7;
}
.a { margin-bottom: 24px; }
.b { margin-top: 16px; }
.centered {
width: 200px;
margin: 16px auto;
} <div class="box a">margin-bottom: 24px</div>
<div class="box b">margin-top: 16px — 24px between the blocks, not 40px</div>
<div class="box centered">margin: 16px auto</div> Result
Good to know
- Vertical margins of adjacent blocks collapse: the larger margin remains, not the sum. There is no collapsing in flex and grid containers.
- margin is space outside the border; the element's background does not reach it. The inner space between the border and the content is padding.
- margin: 0 auto only centers a block whose width or max-width is smaller than its parent.
- Vertical margins on inline elements (span, a) do not push neighbouring lines.
Sources and specification
- MDN: the margin property — MDN Web Docs
- CSS Box Model Module Level 3 (W3C) — W3C
See also
Center an element horizontally and vertically
The simplest modern way to center a block using flexbox.
Build a card with CSS
Practice exercise: build a product card in HTML and link an external stylesheet to it.
The display property
The CSS display property sets how an element takes part in layout: as a block, inline with text, as a flex or grid container, or not at all. Values, examples.
The position property
The CSS position property: how static, relative, absolute, fixed and sticky work, what top and left are measured from and why sticky stops working.
CSS Flexbox for beginners
A beginner's guide to CSS Flexbox: display: flex, axes, justify-content, align-items, flex-wrap, gap and flex: 1, with examples of a menu, cards and centering.
Linking CSS
Lesson 11: three ways to add CSS — an external file via <link rel="stylesheet">, a <style> block in head and the style attribute. Example and task.