/

HTML / CSS / JavaScript Tutorial

CSS Property: top

[this page | pdf | back links]

The CSS (CSS2) top property sets, for absolutely positioned elements, the top edge of an element relative to the corresponding edge of its nearest positioned ancestor. If such an element has no positioned ancestors then it uses the document body and moves along with the page scrolling. A ‘positioned’ element is one whose position is anything other than static.

 

Valid property values (other than inherit and initial) are:

 

Value

Description

length

Sets edge position as a CSS length. Can be negative

%

Sets edge position in % of containing element. Can be negative

auto

(default value). Browser calculates edge position

 

Default Value:

auto

JavaScript syntax:

e.g. object.style.top="10px"

Inherited:

No

Animatable:

Yes

 

EXAMPLE:


HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head>
<style>
div.parent {width: 250px; height: 80px; border: thin solid green; position: relative;}
div.x1 {width: 200px; height: 40px; border: thin solid red;}
div.x2 {width: 200px; height: 40px; border: thin solid red; position: absolute; top: 5px}
</style>
</head>
<body>
<div class="parent">
  <div class="x1">Element with default properties</div>
</div><br>
<div class="parent">
  <div class="x2">Element with CSS property set using HTML</div>
</div><br>
<div class="parent">
  <div id="x3">Element with CSS property set using JavaScript</div>
</div>

<script>
var x = document.getElementById("x3");
x.style.width = "200px";
x.style.height = "40px";
x.style.border = "thin solid red";
x.style.position = "absolute";
x.style.top = "5px";
</script

</body>
</html>

FUNCTION THAT MAY ASSIST IN TESTING WHETHER FEATURE IS SUPPORTED:
function isSupportedCSSPropertyTop() {
  var x = document.createElement("DIV"); x.style.top = "5px"; return (window.getComputedStyle(x, null).top == "5px");
}


NAVIGATION LINKS
Contents | Prev | Next | CSS Properties


Desktop view | Switch to Mobile