Margins are used to create space around elements, outside of any defined borders. The margin property clears an area outside the border of an element.
CSS has properties for specifying the margin for each side of an element:
margin-topmargin-rightmargin-bottommargin-leftp {
margin-top: 40px;
margin-bottom: 20px;
margin-left: 50px;
margin-right: 30px;
}
To keep your CSS code clean, you can specify all margin properties in one single property. The order of the values is: Top, Right, Bottom, Left.
/* Four values: Top, Right, Bottom, Left */
margin: 25px 50px 75px 100px;
/* Three values: Top, Right/Left, Bottom */
margin: 25px 50px 75px;
/* Two values: Top/Bottom, Right/Left */
margin: 10px 20px;
/* One value: All four sides */
margin: 20px;
If you set the margin property to auto, it will horizontally center an 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.
div {
width: 300px;
margin: auto; /* Centers the box horizontally */
}
Unlike padding, margins can have negative values. This allows you to pull elements closer together or even make them overlap.
p {
margin-top: -10px; /* Pulls the element up */
}
Sometimes the top and bottom margins of elements are collapsed into a single margin that is equal to the largest of the two. This does not happen on left and right margins!