⇧
vadnica-logo
Editor My Blog Password Manager Finance My Services About the Project Telegram O meni O meni

CSS Margin (External Spacing)

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.

EXAMPLE
RESULT
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:
  1. px (pixels): margin: 20px;
  2. em (relative to font size): margin: 2em;
  3. rem (relative to root element font size): margin: 2rem;
  4. vw (percentage of viewport width): margin: 5vw;
  5. vh (percentage of viewport height): margin: 5vh;
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).

Quick Reference: CSS Margin Properties

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
marginmargin: 10px; Shorthand property to set all four sides at once
margin-topmargin-top: 20px; Sets the top margin of an element
margin-rightmargin-right: 15px; Sets the right margin of an element
margin-bottommargin-bottom: 10px; Sets the bottom margin of an element
margin-leftmargin-left: 5px; Sets the left margin of an element
Shorthand Syntaxes
margin: 10pxmargin: 10px; All four sides: 10px
margin: 10px 20pxmargin: 10px 20px; Top/Bottom: 10px, Left/Right: 20px
margin: 10px 20px 30pxmargin: 10px 20px 30px; Top: 10px, Left/Right: 20px, Bottom: 30px
margin: 10px 20px 30px 40pxmargin: 10px 20px 30px 40px; Top: 10px, Right: 20px, Bottom: 30px, Left: 40px
Negative Margins
margin: -10pxmargin-top: -10px; Moves element towards adjacent elements (overlap)
Auto Margins (Centering)
margin: 0 automargin: 0 auto; Centers a block element horizontally (if width is set)