Position
The position property determines how an element is placed on a web page. By default, elements stack naturally one after another. Changing the position allows you to move elements anywhere on the screen using top, bottom, left, and right coordinates.
Types of Position
1.Position:static (The Default)
This is the default value for every element. Elements just follow the natural vertical flow of the page. Moving properties (top, left, etc.) have no effect here.
.normal-text {
position: static; /* Even if you add left: 20px, it will NOT move */
}
2.Position:relative
The element stays in the normal page flow, but you can nudge it away from its original starting position without affecting the elements around it. It also acts as an anchor for absolute children.
.icon {
position: relative;
top: -5px; /* Moves the icon 5 pixels UP from where it normally sits */
}
3.Position:absolute
The element is completely removed from the natural page flow. It positions itself relative to its closest parent container that has a position (like relative). If no parent has a position, it goes all the way up to the browser window.
.product-card {
position: relative; /* Acts as the boundary anchor for the child */
}
.sale-badge {
position: absolute;
top: 10px;
right: 10px; /* Pins the badge 10px from the top and right of the card */
}
4.Position:fixed
The element is removed from the page flow and locked relative to the browser window (viewport). It stays exactly in the same spot on your screen, even when you scroll up and down.
.chat-widget {
position: fixed;
bottom: 20px;
right: 20px; /* Stays glued to the bottom-right corner of the screen while scrolling */
}
5.Position:sticky
It behaves like relative at first while scrolling normally, but switches to fixed once it hits a specific spot on the screen (like the very top).
.table-header {
position: sticky;
top: 0; /* Scrolls normally, but sticks to the absolute top of the screen when reached */
}
z-index
z-index is a CSS property that controls the 3D stacking order of overlapping elements on a web page. It determines which element sits on top and which one stays hidden underneath.
The Golden Rule of z-index
z-index only works on elements that have their position property set to relative, absolute, fixed, or sticky. It will completely fail on default static elements.
How the Numbers Work?
- Higher numbers come to the front.
- Lower (or negative) numbers go to the back.
- If two elements have the same z-index, the one written later in the HTML code will naturally stack on top.
The Tricky Interview Concept: "Stacking Context"
Why is my element with z-index: 9999 sitting behind an element with
z-index: 2?
Think of stacking contexts like folders. If Parent Folder A has a z-index: 1 and Parent Folder B has a z-index: 2, any child inside Folder A—even with a z-index: 9999—can never look higher than Folder B. It is trapped inside its parent's stacking level.
Top comments (0)