CSS Margins - Detailed Overview

Introduction to CSS Margins

The margin property in CSS sets the space outside the border of an element. Margins are used to create space around elements and separate them from other elements.

Margin Width

The margin property sets the width of the margins. For example:

div {
    margin: 20px;
}
Margin width: 20px

Individual Margins

You can set individual margins for each side of an element using margin-top, margin-right, margin-bottom, and margin-left. For example:

div {
    margin-top: 10px;
    margin-right: 20px;
    margin-bottom: 30px;
    margin-left: 40px;
}
Individual margins: top 10px, right 20px, bottom 30px, left 40px

Auto Margin

The margin: auto property is often used to center elements horizontally within a container. For example:

div {
    width: 50%;
    margin: auto;
}
Margin auto: Centered horizontally

Negative Margins

Negative values for margins can be used to pull elements closer together or overlap them. For example:

div {
    margin: -10px;
}
Negative margin: -10px

Margin Collapse

When vertical margins of adjacent block elements meet, they can collapse into a single margin. This is known as margin collapse. For example:

div {
    margin-bottom: 20px;
}
p {
    margin-top: 20px;
}

Margin collapse example