Margins are used to create space around elements, outside of any defined borders.
To shorten the code, it is possile to specify all the margin properties in one property.
You can set the margin property to auto to horizontally center the element within its container.
The element will then take up the specified width, and the remaining space will be split equally between the left and right margins.
Example:
div{
width:350px;
margin:auto;
border:1 px solid black;
}
The margin property can set all four sides (top, right, bottom, left) in a single line.
Example:
div{
margin: 10px 15px 20px 25px; /* top, right, bottom, left */
}
Define each side’s margin separately with margin-top, margin-right, margin-bottom, and margin-left.
Example:
div {
margin-top: 20px;
margin-right: 10px;
}
Setting margin: auto; centers the element horizontally within its container (useful for block elements with a defined width).
Example:
div {
width: 50%;
margin: auto;
}
Margins can be negative, which pulls the element closer to surrounding elements.
Example:
div {
margin-top: -10px;
}
Adjacent vertical margins (top and bottom) between elements may "collapse" into a single margin equal to the larger of the two. This only happens with vertical margins, not horizontal ones.
Margins can be set using percentages, relative to the width of the containing element.
Example:
div {
margin-left: 5%;
}
Margins do not inherit from parent elements; they apply only to the specific element they are defined on.