The DOM Style margin Property is used to sets or returns the margin of an element.We can set the different size of margins for individual sides(top, right, bottom, left).
Margin properties can have following values:
- Length in cm, px, pt, etc.
- Width % of the element.
- Margin calculated by the browser: auto.
Syntax:
- It is used to set the margin Property.
object.style.margin = "%|length|auto|initial|inherit"
- It is used to get the margin Property.
object.style.margin
Property Values:
Value | Description |
---|
% | Define the length in percentage compare to parent element. |
---|
length | Define the length in length unit. |
---|
auto | It is default value. |
---|
initial | Define the initial default value. |
---|
inherit | inherit from parent element. |
---|
Return Value: It returns a string value which represent the top, right, bottom, left margin of an element.
Example-1:Margin property set to four values 80px 40px 20px 90px that means top = 80px,
right = 40px, bottom = 20px and left = 90px.
html
< html >
< head >
< title >
HTML | DOM Style margin Property
</ title >
< style >
h1 {
coor: green;
}
#GFG {
border: 2px solid green;
}
</ style >
</ head >
< body >
< center >
< h1 >
GEEKSFORGEEKS
</ h1 >
< h2 >
DOM Style margin Property
</ h2 >
< p id = "GFG" >
Margin properties
</ p >
< br >
< BUTTON ONCLICK = "Geeks()" >Submit</ BUTTON >
< script >
function Geeks() {
document.getElementById("GFG").style.margin =
"80px 40px 20px 90px";
}
</ script >
</ body >
</ html >
|
Output :
- Before click on the button:

- After click on the button:

Example-2: Change all four margin to a single margin margin: 25px; denotes top, right, bottom and left = 25px
html
< html >
< head >
< title >
HTML | DOM Style margin Property
</ title >
< style >
h1 {
coor: green;
}
#GFG {
border: 2px solid green;
margin: 60px 20px 90px 100px;
}
</ style >
</ head >
< body >
< center >
< h1 >
GEEKSFORGEEKS
</ h1 >
< h2 >
DOM Style margin Property
</ h2 >
< p id = "GFG" >
Margin properties
</ p >
< br >
< BUTTON ONCLICK = "Geeks()" >Submit</ BUTTON >
< script >
function Geeks() {
document.getElementById("GFG").style.margin =
"25px";
}
</ script >
</ body >
</ html >
|
Output:
- Before clicking on the button:

- After clicking on the button:

Supported Browsers: The browser supported by DOM Style margin property are listed below:
- Google Chrome 1.0 and above
- Edge 12.0 and above
- Internet Explorer 3.0 and above
- Firefox 1.0 and above
- Opera 3.5 and above
- Apple Safari 1.0 and above