CSS Margins
Margin is the space outside an element, between it and other elements. Margins are always transparent.
.box { margin: 20px; }
Margin for each side and the shorthand
.box {
margin-top: 10px;
margin-right: 20px;
margin-bottom: 30px;
margin-left: 40px;
}
.same { margin: 10px 20px 30px 40px; } /* top right bottom left */
The shorthand works like padding: one, two, three or four values.
Centre a box with margin auto
A block element with a width can be centred by setting the left and right margin to auto.
.container {
width: 300px;
margin: 0 auto;
}
Output in the browser
Centred box
Margin collapse
When the top margin of one block touches the bottom margin of the block above, they do not add. Only the bigger one is used.
.a { margin-bottom: 30px; }
.b { margin-top: 20px; } /* gap between a and b is 30px, not 50px */
Negative margins
A negative margin pulls an element closer, or over another element, like margin-top: -10px. Use it carefully.
Note:
Margins and padding are both “spaces”. Remember: padding is inside the border, and margin is outside the border.
Summary
- Margin is the space outside an element.
margin: 0 autocentres a block with a width.- Vertical margins collapse into the bigger one.
- Next: CSS Box Model.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |