CSS Top property
Top property in CSS:
The top property is used to set the top position of a positioned element.
It works in conjunction with the position property.
Relative Positioning with Top:
div {
position: relative;
top: 20px; /* Move 20 pixels down from its normal position */
}
This example positions the div element 20 pixels down from its normal position within the document flow.
Absolute Positioning with Top:
div {
position: absolute;
top: 50px; /* Position 50 pixels down from the nearest positioned ancestor */
}
In this example, the div element is positioned 50 pixels down from its nearest positioned ancestor.
Fixed Positioning with Top:
div {
position: fixed;
top: 0; /* Fixed to the top edge of the viewport */
}
The div element is fixed to the top edge of the viewport. It will stay in the same position even when the page is scrolled.
Percentage Values:
div {
position: relative;
top: 10%; /* Move 10% of the containing element's height down */
}
This example moves the div element 10% of its containing element's height down.
Negative Values:
div {
position: relative;
top: -30px; /* Move 30 pixels up from its normal position */
}
Negative values for top will move the element up from its normal position.
Combining with Other Properties:
div {
position: absolute;
top: 50px;
left: 20px;
}
This sample illustrates both the `top` and `left` properties which have to values of the element positioned 50 pixels down and 20 pixels right from its nearest positioned ancestor.