🖥 CSS Positioning
When building websites, one of the most important concepts to understand is positioning. The CSS position property lets us control where elements appear on the screen. There are four main types of positioning in CSS:
-
Static
-
Relative
-
Absolute
-
Fixed
Let’s go through each one step by step.
🔹 1. Static Positioning (Default)
-
Every HTML element is static by default.
-
This means elements appear in the order they are written in the HTML (stacked one after another).
-
If you add
top,left,right, orbottomto a static element, nothing happens.
👉 In short: Static = Default flow, no manual positioning.
🔹 2. Relative Positioning
-
With
position: relative;, an element keeps its original place, but you can shift it usingtop,left,right, orbottom. -
The movement is relative to its own default position.
👉 Important: Relative does not mean relative to other elements—it means relative to itself.
🔹 3. Absolute Positioning
-
An element with
position: absolute;is positioned relative to its nearest positioned ancestor (an ancestor withpositionset to relative, absolute, or fixed). -
If no ancestor is positioned, it defaults to the top-left of the entire page.
-
Absolute elements are taken out of the normal HTML flow, so other elements act like it’s not there.
-
With absolute positioning, you can also use z-index to control whether the element sits in front or behind others.
👉 In short: Absolute = Relative to ancestor (or page if none).
🔹 4. Fixed Positioning
-
A fixed element is positioned relative to the browser window, not the page.
-
Even if you scroll, the element stays in the same place.
-
Great for sticky headers, floating buttons, or navigation bars.
👉 In short: Fixed = Stays in place even while scrolling.
🟦 Example: Rectangle with a Circle Inside
Let’s say we want:
-
A blue rectangle (500px wide × 300px tall), placed 200px from the top and 200px from the left.
-
Inside it, a red circle (200px × 200px), positioned 150px from the top and 250px from the left relative to the rectangle.
Solution:
-
Give the rectangle
position: relative; -
Give the circle
position: absolute; top: 150px; left: 250px;
This works because absolute elements look for their nearest positioned ancestor (the rectangle in this case).
🔑 Key Takeaways
-
Static → Default flow, no movement.
-
Relative → Moves relative to its own position.
-
Absolute → Moves relative to the nearest positioned ancestor.
-
Fixed → Moves relative to the browser window (doesn’t scroll).
-
z-index → Controls which element appears on top.

Comments
Post a Comment