CSS Margin
CSS Margin:
Space outside an element is specified by the property called margin.
It use for control the space between the border of an element and its surroundings elements.
Equal Margin on All Sides:
Adds equal margin on all sides of an element.
div {
margin: 10px;
}
Different Margin on Each Side:
Sets different margin values for each side of an element.
section {
margin-top: 20px;
margin-right: 15px;
margin-bottom: 10px;
margin-left: 5px;
}
Shorthand for All Sides:
You can use the shorthand margin property to set margin for all sides in one declaration.
article {
margin: 15px 10px; /* top/bottom: 15px, right/left: 10px */
}
Percentage Margin:
Margin can be specified as a percentage of the width of the containing element.
img {
margin: 5%;
}
Negative Margin:
Negative margins can be used to overlap elements.
h1 {
margin-left: -10px;
}
Auto Margin:
You can use auto to center block-level elements horizontally.
div {
width: 50%;
margin-left: auto;
margin-right: auto;
}
Collapse Margins:
Vertical margins between adjacent block-level elements collapse to the larger of the two margins.
p {
margin-bottom: 20px;
}
/* The margin between paragraphs will be 20px, not the sum of both margins */
These are a few approaches to set margin property at different points such as to make the margin inside, outside or diagonal on the element wrappers.
If it’s needed, you can set the values according to your needs!