CSS margin style attribute
- Previous Page listStyleType
- Next Page marginBottom
- Go to the Previous Level HTML DOM Style Object
Definition and Usage
margin
This attribute sets or returns the outer margin of the element.
This property can take one to four values:
- One value, for example: div {margin: 50px} - All four outer margins are 50px
- Two values, for example: div {margin: 50px 10px} - The top and bottom outer margins are 50px, and the left and right outer margins are 10px
- Three values, for example: 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
- Four values, for example: 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.
Both margin property and padding property insert space around the element. However, the difference is that margin inserts space around the border, while padding inserts space inside the element's border.
See also:
CSS Tutorial:CSS Margin
CSS Reference Manual:Margin property
Example
Example 1
Sets all four margins of the <div> element:
document.getElementById("myDiv").style.margin = "50px 10px 20px 30px";
Example 2
Changes all four margins of the <div> element to "25px":
document.getElementById("myDiv").style.margin = "25px";
Example 3
Returns the margin of the <div> element:
alert(document.getElementById("myDiv").style.margin);
Example 4
Difference between margin property and padding property:
function changeMargin() { document.getElementById("myDiv").style.margin = "100px"; } function changePadding() { document.getElementById("myDiv2").style.padding = "100px"; }
Syntax
Return margin property:
object.style.margin
Set margin property:
object.style.margin = "%|length|auto|initial|inherit"
Attribute value
Value | Description |
---|---|
% | Define the margin as a percentage of the parent element's width. |
length | Define the margin with a length unit. |
auto | Browser sets the margin (all four margins will be equal). |
initial | Sets this property to its default value. See initial. |
inherit | Inherits this property from its parent element. See inherit. |
Technical details
Default value: | 0 |
---|---|
Return value: | A string representing the element's outer margin. |
CSS Version: | CSS1 |
Browser Support
Chrome | Edge | Firefox | Safari | Opera |
---|---|---|---|---|
Chrome | Edge | Firefox | Safari | Opera |
Support | Support | Support | Support | Support |
- Previous Page listStyleType
- Next Page marginBottom
- Go to the Previous Level HTML DOM Style Object