Style margin
Property
Definition and Usage
The margin
property sets or returns the outer margin of an element.
This property can take from 1 to 4 values:
If one value is specified, e.g.,
div {margin: 50px}
- all four outer margins are 50px.If two values are specified, e.g.,
div {margin: 50px 10px}
- the top and bottom outer margins are 50px, and the left and right outer margins are 10px.If three values are specified, e.g.,
div {margin: 50px 10px 20px}
- the top outer margin is 50px, the left and right outer margins are 10px, and the bottom outer margin is 20px.If four values are specified, e.g.,
div {margin: 50px 10px 20px 30px}
- the top outer margin is 50px, the right outer margin is 10px, the bottom outer margin is 20px, and the left outer margin is 30px.
Syntax
Set the margin
property:
Return the margin
property:
Value | Description |
---|---|
% | Defines a percentage margin based on the width of the parent element. |
length | Defines the margin width using units like px, cm, etc. |
auto | The browser sets the margin (all four margins are equal). |
inherit | The margin is inherited from the parent element. |
Browser Support
All major browsers support the margin
property.
Note: IE7 and earlier versions do not support the "inherit" value. IE8 requires a !DOCTYPE to support "inherit". IE9 supports "inherit".
Tips and Notes
Both the margin
and padding
properties insert space around an element. However, the difference is that margin
inserts space outside the border, while padding
inserts space inside the border.
Example
Change the outer margin of a div element: