CSS Position
Control exactly where elements appear on your webpage.
What is CSS Position?
CSS Position is used to control the placement of elements on a webpage. It defines how an element is positioned relative to the document, its parent, or the viewport.
- Move elements anywhere on the page
- Create advanced layouts
- Build navigation bars, popups, and overlays
- Essential for modern UI design
Real-Life Example:
Position is like arranging furniture in a room — you decide where each item stays.
Types of CSS Position
static(default)relativeabsolutefixedsticky
Position: static
Static is the default position of every HTML element. Elements appear in normal document flow.
- Top, right, bottom, left do NOT work
- Follows normal page flow
- No manual movement
Static Position Example
.box {
position: static;
}
Position: relative
Relative positioning moves an element relative to its original position.
- Original space is preserved
- Supports top, right, bottom, left
- Used as reference for absolute elements
Relative Position Example
.box {
position: relative;
top: 20px;
left: 30px;
}
Analogy: Like shifting a chair slightly without changing the room layout.
Position: absolute
Absolute positioning removes the element from normal document flow and positions it relative to the nearest positioned ancestor.
- No space reserved
- Moves freely inside parent
- Depends on nearest relative parent
Absolute Position Example
.parent {
position: relative;
}
.child {
position: absolute;
top: 10px;
right: 10px;
}
Analogy: Like sticking a note on a board at a fixed spot.
Position: fixed
Fixed positioning places an element relative to the browser window.
- Stays visible while scrolling
- Removed from document flow
- Common for navbars & buttons
Fixed Position Example
.navbar {
position: fixed;
top: 0;
width: 100%;
}
Position: sticky
Sticky positioning behaves like relative until a scroll point, then sticks like fixed.
- Combines relative + fixed
- Great for headers
- Requires scroll container
Sticky Position Example
.header {
position: sticky;
top: 0;
}
Analogy: Like a bookmark that follows while reading.
Z-Index with Position
z-index controls the vertical stacking order of positioned elements.
Z-Index Example
.box1 {
position: absolute;
z-index: 1;
}
.box2 {
position: absolute;
z-index: 2;
}
Common Use Cases
- Navigation bars
- Dropdown menus
- Popups & modals
- Tooltips
Best Practices for CSS Position
- Use relative for layout reference
- Avoid excessive absolute usage
- Use sticky instead of JS
- Test responsiveness
Pro Tip: Mastering position unlocks advanced layouts.