CSS Margin Summary
Margin is the empty space outside an element’s border that pushes it away from nearby elements.
.card {
margin: 20px;
}
Margin is part of the CSS box model. It does not change the content inside the element. It changes the space around the element.
Margin Creates Outside Space
Use margin when two boxes need room between them.
h2 {
margin-bottom: 16px;
}
p {
margin-bottom: 20px;
}
The heading and paragraph keep space below themselves, which makes the content easier to scan.
Margin Can Target Each Side
You can set all sides at once or control one side at a time.
.box {
margin: 20px;
margin-top: 40px;
}
Common side properties are margin-top, margin-right, margin-bottom, and margin-left.
Auto Margins Can Center A Fixed-Width Box
When an element has a width, left and right auto margins can center it inside its container.
.wrapper {
max-width: 900px;
margin: 0 auto;
}
The first value controls top and bottom margin. The second value controls left and right margin.
Margin And Padding Are Different
Margin creates space outside a box. Padding creates space inside a box, between the content and the border.