The margin property defines the external spacing of an element – the space between
the element and its neighbors. With margin, we create distance between elements and control their layout. Unlike
padding (internal spacing), which creates space inside an element, margin creates space
outside it. Values can be set for all sides at once or individually for each side.
| Value | Description |
|---|---|
| % (Percentage) | Specifies external spacing in percentages relative to the width of the parent element. For example: margin: 5%; |
| Auto | The browser automatically calculates the spacing. Often used for horizontal centering of elements with a defined width (margin: 0 auto;). |
| Length | Specifies spacing in various units:
|
| initial | Sets the value to the default value according to the CSS specification (for margin, this is 0). |
| inherit | The element inherits the margin value from its parent element (by default margin is not inherited, but can be forced with this value). |
| Negative Values | Negative values are also allowed (e.g., margin: -20px), which move the element in the opposite direction and can cause overlapping of elements. |
| unset | Resets the value – since margin is not an inherited property, it behaves the same as initial (value 0). |
The table below shows all main properties for controlling external margins. Use them to set distances between elements, center blocks, or create negative margins. Examples in the "Example" column are ready for direct copying into your CSS.
| Property | Example | Description |
|---|---|---|
| Basic Properties | ||
margin | margin: 10px; |
Shorthand property to set all four sides at once |
margin-top | margin-top: 20px; |
Sets the top margin of an element |
margin-right | margin-right: 15px; |
Sets the right margin of an element |
margin-bottom | margin-bottom: 10px; |
Sets the bottom margin of an element |
margin-left | margin-left: 5px; |
Sets the left margin of an element |
| Shorthand Syntaxes | ||
margin: 10px | margin: 10px; |
All four sides: 10px |
margin: 10px 20px | margin: 10px 20px; |
Top/Bottom: 10px, Left/Right: 20px |
margin: 10px 20px 30px | margin: 10px 20px 30px; |
Top: 10px, Left/Right: 20px, Bottom: 30px |
margin: 10px 20px 30px 40px | margin: 10px 20px 30px 40px; |
Top: 10px, Right: 20px, Bottom: 30px, Left: 40px |
| Negative Margins | ||
margin: -10px | margin-top: -10px; |
Moves element towards adjacent elements (overlap) |
| Auto Margins (Centering) | ||
margin: 0 auto | margin: 0 auto; |
Centers a block element horizontally (if width is set) |