CSS Margins

What are Margins?

Margins are used to create space around elements, outside of any defined borders. They are part of the CSS box model.

Margin Properties

Individual Sides

Example
div {
    margin-top: 20px;
    margin-right: 15px;
    margin-bottom: 20px;
    margin-left: 15px;
}

Shorthand - All Sides

Example
div {
    margin: 20px;  /* All sides */
}

Shorthand - Vertical and Horizontal

Example
div {
    margin: 20px 10px;  /* top/bottom left/right */
}

Shorthand - All Four Sides

Example
div {
    margin: 10px 20px 30px 40px;  /* top right bottom left */
}

Auto Margin

Using margin: auto centers an element horizontally:

Example
div {
    width: 300px;
    margin: 0 auto;  /* Centers horizontally */
}

Negative Margins

You can use negative values to overlap elements:

Example
div {
    margin: -10px;
}

Margin Collapse

When two vertical margins meet, they collapse into a single margin equal to the larger of the two margins.