When building web layouts, understanding CSS positioning is essential. It helps you control where and how elements appear on the page. In this blog, we'll explore the five main types of positioning in CSS: static
, relative
, absolute
, fixed
, and sticky
.
πΉ 1. static
Position (Default)
This is the default position for all HTML elements. With static
, elements follow the normal document flow.
div {
position: static;
}
πΈ Note: You can't use top
, left
, right
, or bottom
with static
.
πΉ 2. relative
Position
relative
positions the element relative to its normal position. You can shift it using top
, left
, right
, or bottom
.
div {
position: relative;
top: 20px;
left: 10px;
}
β The element still takes up space in the layout, even if it moves visually.
πΉ 3. absolute
Position
absolute
removes the element from the normal flow and positions it relative to the nearest positioned ancestor (relative
, absolute
, fixed
, or sticky
).
div {
position: absolute;
top: 0;
left: 0;
}
π If there's no positioned ancestor, it will be placed relative to the <html>
or <body>
.
πΉ 4. fixed
Position
fixed
positions the element relative to the viewport, so it stays in place even when the page scrolls.
div {
position: fixed;
bottom: 0;
right: 0;
}
β¨ Often used for sticky navbars, chat widgets, or back-to-top buttons.
πΉ 5. sticky
Position
A combination of relative
and fixed
. The element behaves like relative
until it reaches a certain scroll position, then it sticks like fixed
.
div {
position: sticky;
top: 0;
}
π Perfect for sticky headers or table columns.
π Example Summary
Position | Keeps Layout Space? | Scrolls with Page? | Relative To |
---|---|---|---|
static |
β Yes | β Yes | Normal document flow |
relative |
β Yes | β Yes | Its original position |
absolute |
β No | β No | Nearest positioned parent |
fixed |
β No | β No | Viewport |
sticky |
β Yes (initially) | β οΈ Sometimes | Scroll container / viewport |
π§ Final Tips
- Use
relative
to adjust an element slightly without affecting the flow. - Use
absolute
when you want full control inside a container. - Use
fixed
for UI elements that need to stay visible. - Use
sticky
to enhance user experience during scroll.
Top comments (3)
Thanks, bro. To add on, here are some great, fun websites to practice CSS positioning:
thanks bro for your information and i already finished all levels in flexbox froggy and grid garden ...i will try flexbox defenseπ
Woohoo, thatβs awesome, bro! Great jobβwell done!