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
relativeto adjust an element slightly without affecting the flow. - Use
absolutewhen you want full control inside a container. - Use
fixedfor UI elements that need to stay visible. - Use
stickyto 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!