CSS Position
31 March 2025 | Category: CSS
The position
property in CSS is used to control the positioning of an element on a webpage. It allows elements to be placed relative to other elements, the viewport, or in a fixed location.
1️⃣ Syntax
selector {
position: value;
}
✅ Possible Values
Value | Description |
---|---|
static | Default positioning (normal document flow). |
relative | Moves relative to its normal position. |
absolute | Moves relative to the nearest positioned ancestor. |
fixed | Stays in place even when scrolling (relative to the viewport). |
sticky | Toggles between relative and fixed based on scroll position. |
2️⃣ position: static
(Default Behavior)
📌 Elements follow normal document flow (cannot be moved using top
, left
, etc.).
.box {
position: static;
top: 20px; /* ❌ This will not work */
}
✅ Example:
<div class="box">I am static (default behavior)</div>
3️⃣ position: relative
📌 Moves the element relative to its normal position.
.box {
position: relative;
top: 20px; /* Moves down */
left: 30px; /* Moves right */
}
✅ Example:
<div class="box">I am relative (moved 20px down and 30px right)</div>
4️⃣ position: absolute
📌 Moves the element relative to the nearest positioned ancestor (if none, relative to body
).
.box {
position: absolute;
top: 50px;
left: 50px;
}
✅ Example:
<div class="parent" style="position: relative; width: 200px; height: 200px; background: lightgray;">
<div class="box">I am absolute</div>
</div>
📌 Notes:
- If
position: absolute
is used inside arelative
parent, it moves relative to that parent.
5️⃣ position: fixed
📌 Stays in place even when scrolling (relative to the viewport).
.box {
position: fixed;
top: 10px;
right: 10px;
}
✅ Example: (Fixed navbar)
<div class="navbar">I am fixed at the top!</div>
📌 Use case: Sticky headers, floating buttons, chat popups.
6️⃣ position: sticky
📌 Acts like relative
but becomes fixed
when scrolled past a threshold.
.box {
position: sticky;
top: 0px;
}
✅ Example: (Sticky header)
<div class="header">I stick to the top when scrolling!</div>
7️⃣ z-index
– Controlling Layer Order
📌 z-index
decides which element appears on top.
.box1 {
position: absolute;
z-index: 10; /* Higher number appears on top */
}
.box2 {
position: absolute;
z-index: 5; /* Lower number appears below */
}
✅ Use case: Popups, tooltips, dropdown menus.
🎯 Summary
position Value | Behavior |
---|---|
static | Default positioning (normal flow). |
relative | Moves relative to its normal position. |
absolute | Moves relative to the nearest positioned ancestor. |
fixed | Stays fixed in the viewport. |
sticky | Sticks to a position when scrolling. |
💡 Use the position
property to create dynamic layouts! 🚀