The margin property declares the margin between an (X)HTML element and the elements around it. The margin property can be set for the top, left, right and bottom of an element.
There are 3 values for the margin property:
Examples,
margin-top: length, percentage or auto;
margin -left: length, percentage or auto;
margin -right: length, percentage or auto;
margin -bottom: length, percentage or auto;
You can also declare all the margins of an element in a single property as follows:
margin: 10px 10px 10px 10px;
If you declare all 4 values as above, the order is:
If only one value is declared, it sets the margin on all sides:
margin: 10px;
If you only declare two or three values, the undeclared values are taken from the opposing sides.
You can also set the margin property to negative values.
margin: -10px;
If you do not declare the margin value of an element, the margin is 0 (zero). Elements like paragraphs have default margins in some browsers, you can set the margin to 0 (zero) to combat this.
margin: 0px;
Example of CSS margins:
body {
margin: 20px;
background: #eeeeee;
font-size: small;
font-family: Arial, Tahoma, sans-serif;
text-align: left;
}
Padding is the distance between the border of an element and the content within it.
Most of the rules for margins also apply to padding, except there is no “auto” value and negative values cannot be declared for padding.
The 2 values for the padding property:
You can also declare all the padding of an element in a single property.
padding: 10px 10px 10px 10px;
If you declare all 4 values, the order is:
If only one value is declared, it sets the padding on all sides:
padding: 10px;
If you only declare two or three values, the undeclared values are taken from the opposing sides.
If you do not declare the padding value of an element, the margin is 0 (zero).
Example of CSS padding:
container {
width: 90%;
margin: auto;
padding: 20px;
border: 1px solid #555;
background: #eeeeee;
}