Margin & Padding in CSS
Margin and padding are two key spacing properties in CSS. They control the space around and inside elements, and are essential for layout and design.
1. Margin
The margin
property sets the outer space around an element. It pushes the element away from others.
.box {
margin: 20px;
}
You can set individual sides using:
margin-top
margin-right
margin-bottom
margin-left
Or use shorthand: margin: 10px 15px 20px 25px;
(top, right, bottom, left)
2. Padding
The padding
property adds space inside the element, between the content and the border.
.card {
padding: 16px;
}
You can also target individual sides: padding-top
, padding-right
, etc.
Or use shorthand like padding: 10px 20px;
for top-bottom and left-right.
3. Margin Collapse
When vertical margins of two elements meet, the larger one remains and the smaller one collapses. This is called margin collapsing.
h1 {
margin-bottom: 20px;
}
p {
margin-top: 10px;
}
/* Result: total margin between h1 and p is 20px, not 30px */
4. Best Practices
- Use margin for spacing between elements.
- Use padding for spacing inside elements (around content).
- Consistent use of shorthand improves readability.
- Use
box-sizing: border-box
to make padding and border part of total width/height.
Conclusion
Mastering margin and padding is crucial for creating clean and well-structured web layouts. Use them wisely to control spacing and improve design flow.