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.
The margin
property sets the width of the margins. For example:
div {
margin: 20px;
}
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;
}
The margin: auto
property is often used to center elements horizontally within a container. For example:
div {
width: 50%;
margin: auto;
}
Negative values for margins can be used to pull elements closer together or overlap them. For example:
div {
margin: -10px;
}
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