CSS top Property

CSS top property specifies the vertical position of a positioned element in the layout. It basically specifies the position of the top edge of an element.

The top property has no effect on non-positioned elements. An element is called non-positioned if its status is static. That is, the top property will not affect elements having position: static;.

The effect of the top property varies with the position of the element i.e.

  • If the position of the element is relative, the element adjusts itself relative to its original(default) position.

In the example below, the <div> element moves 60px below from its original(default) position, as we have specified top: 60px; Try it out:

Example:

div{
  position: relative;
  top: 60px;
}

  • If the position of the element is absolute, the element adjusts itself relative to the nearest positioned ancestor. If the element has no positioned ancestor, it adjusts itself relative to the viewport.

In the example below, the <div> element places itself 50px below from the viewport, as it has no positioned ancestor. Try it out:

Example:

div{
  position: absolute;
  top: 50px;
}

  • If the position of the element is set to fixed, the element adjusts itself relative to the viewport. Also, the element will always be fixed and it will not scroll along with the webpage.

In the example below, the <div> element places itself 200px below from the viewport and remains fixed on that position even if you scroll down the webpage. Try it out:

Example:

div{
  position: fixed;
  top: 200px;
}

CSS Syntax

The top property has the below syntax:

top: auto|length|%|initial|inherit;

Property Values

The top property accepts the following values:

autoThe browser itself calculates the top position of the element. This is the default value.
lengthSpecifies the top position of the element in a valid CSS length format such as ‘px’, ’em’, ‘rem’, ‘cm’, etc. Negative values are also allowed.
%Specifies the top position of the element in percentage(%). The percentage value is calculated from the parent element’s total height.
initialSets the top property to its default value(auto).
inheritInherits the top property from the parent element.

general Info

Default Valueauto
InheritedNo
JavaScript Usageelement.style.top= “60px”;