CSS top

The CSS top property is used to define the vertical position of an element, from the top edge. This property only effects on positioned element. For example:

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
   <style>
      .a{position: relative; width: 220px; height: 120px; border: 2px solid red;}
      .b{position: absolute; top: 40px; color: blue;}
   </style>
</head>
<body>

   <div class="a">
      <div class="b">CODESCRACKER</div>
   </div>

</body>
</html>
Output
CODESCRACKER

In above example, with the help of top: 40px, the element moved down by 40px from the top edge.

Note - The position property defines the position category of an element.

CSS top Syntax

The syntax of top property in CSS, is:

top: x;

The value of x should be any of the following:

  • Length - Used to move an element by some custom length like 12px, 2cm etc. from the top edge
  • auto - Used to allow browser to define the top position of an element automatically. This is the default value
  • initial - Used to use the default value
  • inherit - Used to use the value inherited by the parent element

CSS top Example

<!DOCTYPE html>
<html>
<head>
   <style>
      .a{position: fixed; top: 300px; background-color: red;
         color: whitesmoke; padding: 8px;}
      .b{position: relative; width: 260px; height: 220px;
         background-color: blue; color: whitesmoke;
         top: 20px; padding: 8px;}
      .c{position: absolute; top: 60px; background-color: green;
         color: whitesmoke; padding: 8px;}
   </style>
</head>
<body>

   <div class="a">position: fixed; top: 300px</div>
   <div class="b">position: relative; top: 20px
      <div class="c">position: absolute; top: 60px</div>
   </div>

</body>
</html>

The output produced by above example is:

css top property example

Note - Giving negative value to the top property, will move an element up from the top edge. For example:

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
   <style>
      .a{position: relative; width: 260px; height: 120px; padding: 8px;
         background-color: gray; color: whitesmoke;}
      .x, .y{position: absolute; background-color: green; color: whitesmoke;
         padding: 8px;}
      .x{top: 20px;}
      .y{top: -20px;}
   </style>
</head>
<body>

   <h2>top: 20px</h2>
   <div class="a">
      <div class="x">position: absolute; top: 20px</div>
   </div>

   <h2>top: -20px</h2>
   <div class="a">
      <div class="y">position: absolute; top: -20px</div>
   </div>

</body>
</html>
Output

top: 20px

position: absolute; top: 20px

top: -20px

position: absolute; top: -20px

CSS Online Test


« Previous Tutorial Next Tutorial »



Like/Share Us on Facebook 😋