Margin clears an area around the border that separates it from other boxes.
CSS Margin Properties
The CSS margin properties allow you to set the margins around the sides of an element’s box. The margins does not have a background-color
, it is completely transparent.
Setting Margins for Individual Sides
You can easily specify the different margins for the different sides of an element such as top, right, bottom or left side using the CSS individual margin property.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<!DOCTYPE html> <html lang="en"> <head> <title>Example of CSS margin Property</title> <style type="text/css"> h1 { margin-bottom: 20px; } p { margin-left: 10px; margin-right: 30px; } </style> </head> <body> <h1>This is a heading</h1> <p>This is a paragraph.</p> <p><strong>Note:</strong> Change the margin property value to see how it works.</p> </body> </html> |
The margin Shorthand Property
The margin
property is a shorthand property to avoid setting margin of each side separately:margin-top
, margin-right
, margin-bottom
and margin-left
.
1 2 3 4 5 6 |
h1 { margin: 0 10px; } p { margin: 25px 50px 75px 100px; } |
This shorthand notation can take one, two, three, or four whitespace separated values.
- If one value is set, this is applied to all the four sides.
- If two values are specified, the first value is applied to the top and bottom, and the second value is applied to the right and left side.
- If three values are specified, the first value is applied to the top, second value is applied to left and right side and the last value is applied to the bottom.
- If four values are specified, they are applied to the top, right, bottom and the left side respectively in the specified order.