CSS

CSS (Cascading Style Sheets) is the language that brings web pages to life with colors, layouts, and animations. It works alongside HTML to create visually stunning and responsive designs. Let's explore the power of CSS.

CSS Position

31 March 2025 | Category:

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

ValueDescription
staticDefault positioning (normal document flow).
relativeMoves relative to its normal position.
absoluteMoves relative to the nearest positioned ancestor.
fixedStays in place even when scrolling (relative to the viewport).
stickyToggles 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 a relative 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 ValueBehavior
staticDefault positioning (normal flow).
relativeMoves relative to its normal position.
absoluteMoves relative to the nearest positioned ancestor.
fixedStays fixed in the viewport.
stickySticks to a position when scrolling.

💡 Use the position property to create dynamic layouts! 🚀