📍 CSS top
— Position Elements Vertically
The top
property in CSS defines the vertical position of a positioned element (e.g., absolute, relative, fixed, sticky). It controls how far the element’s top edge moves from its reference point — such as the top of its containing block.
🔹 When Does top
Work?
The top
property only works when the element’s position
is set to:
relative
absolute
fixed
sticky
🛑 It does not affect elements with position: static
(the default).
📘 Syntax
selector {
position: relative | absolute | fixed | sticky;
top: <length> | <percentage> | auto | inherit;
}
💡 Value Types
Value | Description |
---|---|
<length> | Moves the element down by that distance (e.g. 20px , 2em ) |
<%> | Based on the height of the containing block |
auto | Default value; browser decides the top position |
inherit | Inherits the top value from the parent |
✍️ Example: Moving an Element Down Using top
<div class="move-down">I'm moved down by 50px!</div>
.move-down {
position: relative;
top: 50px;
}
✅ The element stays in normal flow but shifts down 50px.
✍️ Example: Precise Placement with absolute
<div class="container">
<div class="badge">New</div>
</div>
.container {
position: relative;
}
.badge {
position: absolute;
top: 10px;
right: 10px;
}
✅ The badge appears 10px from the top of the container — perfect for labels or alerts.
🖼️ Image Idea: Side-by-Side Layout
Example | position: relative; top: 0px; | top: 50px; | top: -20px; |
---|---|---|---|
Visual | Normal position | Moved down | Moved up |
🎯 Purpose: Show how the element’s vertical location changes with top
.
🧠 How top
Interacts with Other position
Values
position | Effect of top |
---|---|
static | ❌ No effect |
relative | ✅ Shifts the element visually only |
absolute | ✅ Moves relative to nearest positioned ancestor |
fixed | ✅ Moves relative to viewport |
sticky | ✅ Behaves like relative until “stuck” |
✅ Best Use Cases
Use Case | How top Helps |
---|---|
Tooltip placement | Offset tooltips near targets |
Sticky headers | Pin headers at top using top: 0 |
Absolute positioning | Align badges, overlays, buttons |
Animation start position | Use top in keyframe animations |
✅ Summary
Property | top |
---|---|
Purpose | Vertically offset positioned elements |
Works with | relative , absolute , fixed , sticky |
Common units | px , em , % |
Doesn’t work | On static elements (default position) |
⚠️ Pro Tip
When using top
with absolute
or fixed
, always ensure the parent element has position: relative
(or another non-static position), so the child knows what to position against.
🔚 Final Thought
The top
property is essential for fine-tuned vertical control in CSS layouts. Whether you’re building sticky headers, tooltips, or floating buttons — it’s a precise and powerful tool in your layout toolbox.