CSS Margin
The CSS margin properties are used to create space around elements, outside of any defined borders. With CSS, you have full control over the margins. There are properties for setting the margin for each side of an element (top, right, bottom, and left).
Parameter | Details |
---|---|
0 | set margin to none |
auto | used for centering, by evenly setting values on each side |
units (e.g. px) | see parameter section in Units for a list of valid units |
inherit | inherit margin value from parent element |
initial | restore to initial value |
Margin Collapsing
When two margins are touching each other vertically, they are collapsed. When two margins touch horizontally, they do not collapse.
div{
margin: 10px;
}
They will be 10px apart since vertical margins collapse over one and other. (The spacing will not be the sum of two margins.)
Overlapping with different sizes
.top{
margin: 10px;
}
.bottom{
margin: 15px;
}
These elements will be spaced 15px apart vertically. The margins overlap as much as they can, but the larger margin will determine the spacing between the elements./p>