Stylemargin Property
Example
Set all four margins of a <div> element:
Description
The margin property sets or returns the margins of an element.
This property can take from one to four values:
- One value, like: div {margin: 50px} - all four margins will be 50px
- Two values, like: div {margin: 50px 10px} - the top and bottom margins will be 50px, left and right margins will be 10px
- Three values, like: div {margin: 50px 10px 20px}- the top margin will be 50px, left and right margin will be 10px, bottom margin will be 20px
- Four values, like: div {margin: 50px 10px 20px 30px} - the top margin will be 50px, right margin will be 10px, bottom margin will be 20px, left margin will be 30px
Both the margin property and the padding property insert space around an element. However, the difference is that margin inserts the space around the border, while padding inserts the space within the border of an element.
Browser Support
| Property | |||||
|---|---|---|---|---|---|
| margin | Yes | Yes | Yes | Yes | Yes |
Syntax
Return the margin property:
Set the margin property:
Property Values
| Value | Description |
|---|---|
| % | Defines the margins in % of the width of the parent element |
| length | Defines the margins in length units |
| auto | The browser sets the margins (all four margins will be equal) |
| initial | Sets this property to its default value.Read aboutinitial |
| inherit | Inherits this property from its parent element.Read aboutinherit |
Technical Details
| Default Value: | 0 |
|---|---|
| Return Value: | A String, representing the margins of an element |
| CSS Version | CSS1 |
More Examples
Example
Change all four margins of a <div> element to "25px":
Example
Return the margins of a <div> element:
Example
Difference between the margin property and the padding property:
document.getElementById("myDiv").style.margin = "100px";
}
function changePadding() {
document.getElementById("myDiv2").style.padding = "100px";
}
Related Pages
CSS tutorial:CSS Margin
CSS reference:margin property

