Javascript Reference - HTML DOM Style marginTop Property








The marginTop property sets or gets the top margin of an element.

Browser Support

marginTop Yes Yes Yes Yes Yes

Syntax

Return the marginTop property:

var v = object.style.marginTop 

Set the marginTop property:

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

Property Values

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




Technical Details

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

Example

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


<!DOCTYPE html>
<html>
<head>
<style>
#myDiv {<!--   w  w  w  . java2s  .c o  m-->
    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.marginTop = "200px";
}
</script>
</body>
</html>

The code above is rendered as follows:





Example 2

The following code shows how to change the top margin.


<!DOCTYPE html>
<html>
<head>
<style>
#myDiv {<!-- w  w  w .  ja  v a 2 s  .  c o m-->
    border: 1px solid #FF0000;
    margin-top: 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.marginTop = "10px";
}
</script>
</body>
</html>

The code above is rendered as follows:

Example 3

The following code shows how to get the top margin.


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

The code above is rendered as follows:

Example 4

The following code shows how to set marginTop and paddingTop.


<!DOCTYPE html>
<html>
<head>
<style>
div {<!--from w w w . ja v a2 s . c o m-->
    border: 1px solid black;
}
</style>
</head>
<body>

<div id="myDiv">This is some text.</div>
<button type="button" onclick="changeMargin()">top margin</button>
<div id="myDiv2">This is some text.</div>
<button type="button" onclick="changePadding()">top padding</button>

<script>
function changeMargin() {
    document.getElementById("myDiv").style.marginTop = "200px";
}

function changePadding() {
    document.getElementById("myDiv2").style.paddingTop = "200px";
}
</script>

</body>
</html>

The code above is rendered as follows: