Javascript Reference - HTML DOM Style marginRight Property








The marginRight property sets or gets the right margin of an element.

Browser Support

marginRight Yes Yes Yes Yes Yes

Syntax

Return the marginRight property:

var v = object.style.marginRight 

Set the marginRight property:

object.style.marginRight='%|length|auto|initial|inherit'

Property Values

Value Description
% Set the right margin in percent of the container element width
length Set the right margin in length units
auto Let browser set the right margin
initial Set to default value.
inherit Inherits from its parent element.




Technical Details

Default Value: 0
Return Value: A string representing the right margin
CSS Version CSS1

Example

The following code shows how to set the right margin of a <div> element:


<!DOCTYPE html>
<html>
<head>
<style>
#myDiv {<!--from w  w  w  .j  a  v a 2s.c  om-->
    border: 1px solid #FF0000;
}
</style>
</head>
<body>
<div id="myDiv">This is a div.</div>
<button type="button" onclick="myFunction()">test</button>
<script>
function myFunction() {
    document.getElementById("myDiv").style.marginRight = "50px";
}
</script>
</body>
</html>

The code above is rendered as follows:





Example 2

The following code shows how to change the right margin of a <div> element.


<!DOCTYPE html>
<html>
<head>
<style>
#myDiv {<!--from   w w w .j a  va2 s  . co m-->
    border: 1px solid #FF0000;
    margin-right: 75px;
}
</style>
</head>
<body>

<div id="myDiv">This is a div.</div>
<br>
<button type="button" onclick="myFunction()">Change right margin</button>

<script>
function myFunction() {
    document.getElementById("myDiv").style.marginRight = "20px";
}
</script>

</body>
</html>

The code above is rendered as follows:

Example 3

The following code shows how to get the right margin of a <div> element:


<!DOCTYPE html>
<html>
<head>
<style>
#myDiv {<!--from  w w w  .ja va 2 s  .c  o  m-->
    border: 1px solid #FF0000;
}
</style>
</head>
<body>
<div id="myDiv" style="margin-right:5cm;">This is a div.</div>
<button type="button" onclick="myFunction()">right margin</button>
<script>
function myFunction() {
    console.log(document.getElementById("myDiv").style.marginRight);
}
</script>
</body>
</html>

The code above is rendered as follows:

Example 4

The following code shows how to set marginRight and paddingRight.


<!DOCTYPE html>
<html>
<head>
<style>
div {<!--from   www .j  a v a2  s  .c  om-->
    border: 1px solid black;
}
</style>
</head>
<body>
<div id="myDIV">this is a div</div>
<button type="button" onclick="changeMargin()">right margin</button>
<div id="myDIV2">div</div>
<button type="button" onclick="changePadding()">right padding</button>
<script>
function changeMargin() {
    document.getElementById("myDIV").style.marginRight = "400px";
}

function changePadding() {
    document.getElementById("myDIV2").style.paddingRight = "400px";
}
</script>
</body>
</html>

The code above is rendered as follows: