Javascript Reference - HTML DOM Style marginLeft Property








The marginLeft property sets or gets the left margin of an element.

Browser Support

marginLeft Yes Yes Yes Yes Yes

Syntax

Return the marginLeft property:

var v = object.style.marginLeft;

Set the marginLeft property:

object.style.marginLeft='%|length|auto|inherit'

Property Values

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




Technical Details

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

Example

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


<!DOCTYPE html>
<html>
<head>
<style>
#myDiv {<!--  w  w w . j  a  v a  2 s . com-->
    border: 1px solid black;
}
</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.marginLeft = "100px";
}
</script>
</body>
</html>

The code above is rendered as follows:





Example 2

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


<!DOCTYPE html>
<html>
<head>
<style>
#myDiv {<!--from   w ww .j  a va  2s. c o  m-->
    border: 1px solid #FF0000;
    margin-left: 75px;
}
</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.marginLeft = "10px";
}
</script>

</body>
</html>

The code above is rendered as follows:

Example 3

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


<!DOCTYPE html>
<html>
<head>
<style>
#myDiv {<!-- www. jav a2  s .c o  m-->
    border: 1px solid #FF0000;
}
</style>
</head>
<body>
<div id="myDiv" style="margin-left:5cm;">This is a div.</div>
<button type="button" onclick="myFunction()">test</button>
<script>
function myFunction() {
    console.log(document.getElementById("myDiv").style.marginLeft);
}
</script>
</body>
</html>

The code above is rendered as follows:

Example 4

The following code shows how to set marginLeft and paddingLeft.


<!DOCTYPE html>
<html>
<head>
<style>
div {<!--   ww w .  j  av a2  s . c  o m-->
    border: 1px solid #FF0000;
}
</style>
</head>
<body>
<div id="myDiv">This is some text.</div>
<button type="button" onclick="changeMargin()">left margin</button>
<div id="myDiv2">This is some text.</div>
<button type="button" onclick="changePadding()">left padding</button>
<script>
function changeMargin() {
    document.getElementById("myDiv").style.marginLeft = "50px";
}
function changePadding() {
    document.getElementById("myDiv2").style.paddingLeft = "50px";
}
</script>
</body>
</html>

The code above is rendered as follows: