CSS Margins
CSS Margins
CSS margins are used to create space outside elements. Margins control the distance between an element and the elements around it.
Unlike padding, margins do not affect the size of the element itself.
Margins
The margin property can be used to set space on all four sides of an element.
.box {
margin: 20px;
}
You can also set margins for each side individually:
.box {
margin-top: 10px;
margin-right: 20px;
margin-bottom: 30px;
margin-left: 40px;
}
Margin Shorthand
Margin shorthand allows you to define multiple sides in one line.
/* top right bottom left */
.box {
margin: 10px 20px 30px 40px;
}
/* top-bottom left-right */
.box {
margin: 20px 40px;
}
Auto Margins
Using margin: auto is a common technique to center block-level elements horizontally.
.container {
width: 400px;
margin: auto;
}
Margin Collapse
Vertical margins of adjacent block elements may collapse into a single margin. This behavior is called margin collapse.
Only vertical margins (top and bottom) collapse. Horizontal margins do not.
h2 {
margin-bottom: 30px;
}
p {
margin-top: 20px;
}
Instead of adding up to 50px, the margins collapse and the result is 30px.
Preventing Margin Collapse
Margin collapse can be prevented by adding padding or a border to the parent element.
.wrapper {
padding: 1px;
}
Code Challenge
Goal: Use margins to space the elements below.
HTML:
<div class="card"> <h3>Title</h3> <p>This card uses margins.</p> </div>
Task:
- Add space around the card
- Add extra space below the heading
- Center the card horizontally
Try a Solution:
.card {
width: 420px;
margin: 40px auto;
}
.card h3 {
margin-bottom: 16px;
}
What’s Next?
Next, you will learn how to control spacing inside elements using CSS padding.