Javascript Reference - HTML DOM Style top Property








The top property sets or gets the top position of a positioned element.

Browser Support

top Yes Yes Yes Yes Yes

Syntax

Return the top property:

var v = object.style.top 

Set the top property:

oject.style.top='auto|length|%|initial|inherit'

Property Values

Value Description
auto Browser will decide how to set the top position. Default
length Set the top position in length units. Negative values are allowed
% Set the top position in percent of the height of the container element
initial Set to default value.
inherit Inherit from parent element.




Technical Details

Default Value: auto
Return Value: A string representing the top position
CSS Version CSS2

Example

The following code shows how to set the top position.


<!DOCTYPE html>
<html>
<head>
<style>
#myBtn {<!--   w  w w  . ja  v a 2 s.c  o  m-->
    position: absolute;
}
</style>
</head>
<body>
<button type="button" id="myBtn" onclick="myFunction()">test</button>
<script>
function myFunction() {
    document.getElementById("myBtn").style.top = "100px";
}
</script>

</body>
</html>

The code above is rendered as follows:





Example 2

The following code shows how to use negative values to set the top position.


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

</body>
</html>

The code above is rendered as follows:

Example 3

The following code shows how to get the top position.


<!DOCTYPE html>
<html>
<body>
<div id="myDiv" style="position:absolute;top:75px;">This is a div.</div>
<button type="button" onclick="myFunction()">test</button>
<script>
function myFunction() {<!--from   www . j  a va  2  s  .c  om-->
    console.log(document.getElementById("myDiv").style.top);
}
</script>
</body>
</html>

The code above is rendered as follows: