CSS top property

The top property defines the top position of an element in combination with the position property.

The effect of the top property depends on how the element is positioned (see position property).

  • If position is set to "absolute" or "fixed", the top property specifies the top edge of an element to a unit above/below the top edge of its nearest positioned ancestor.
  • If position is set to "relative", the top property specifies the top edge to move above/below its normal position.
  • If position is set to "sticky", the top property changes its position to relative when the element is inside the viewport, and changes to fixed when it is outside.
  • When the position property is set to "static", the position property is not applied.

Negative values are allowed.

Initial Value auto
Applies to Positioned elements.
Inherited No.
Animatable Yes.
Version CSS2
DOM Syntax Object.style.top = "50px";

Syntax

top: auto | length | initial | inherit;

Example

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      div {
      background-color: #8ebf42;
      height: 200px;
      width: 600px;
      position:relative;
      }
      p {
      color: #eee;
      position: absolute;
      border: 2px solid #666;
      }
      .ex1 {
      top: 0;
      }
      .ex2 {
      top: 50px;
      }
    </style>
  </head>
  <body>
    <h2>Top property example</h2>
    <div>
      <p class="ex1">Some text (top: 0;)</p>
      <p class="ex2">Lorem ipsum is simply dummy text...(this text is positioned 50 pixels down from the top edge of the containing positioned element.)</p>
    </div>
  </body>
</html>

An example where a negative value is specified:

Example

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      div {
      background-color: #666;
      height: 200px;
      position: relative;
      }
      p {
      color: #fff;
      }
      .top{
      position: absolute;
      top: -35px;
      color: #000000;
      }
    </style>
  </head>
  <body>
    <h2>Top property example</h2>
    <div>
      <p>Some text.</p>
      <p class="top">Text with the top property.</p>
    </div>
  </body>
</html>

Property Values

Value Descriptions
auto Sets the top edge position. It is the default value of this property.
length Sets the top edge position with px, cm etc. Negative values are valid.
% Sets the top edge position with % of containing element. Negative values are valid.
initial Makes the property use its default value.
inherit Inherits the property from its parents element.




Related articles