Perfectβnow weβre entering real layout control in CSS. Positioning is what allows you to place elements exactly where you want.
π CSS COURSE β MODULE 7: POSITIONING
π File: position.md
π CSS Positioning
π Introduction
The position property controls how an element is placed on the page.
π It allows you to:
- move elements anywhere
- overlap elements
- fix elements on screen
- create modern UI layouts
π§ 1. Static (Default)
div {
position: static;
}
π Behavior:
- Default position
- Follows normal document flow
β You usually donβt use it manually
π 2. Relative Position
div {
position: relative;
top: 10px;
left: 20px;
}
π Behavior:
- Moves element from its original position
- Keeps original space reserved
π¦ 3. Absolute Position
div {
position: absolute;
top: 0;
left: 0;
}
π Behavior:
- Removed from normal flow
- Positioned relative to nearest parent
π§± Important Rule
π Absolute works relative to a parent with:
position: relative;
π 4. Fixed Position
div {
position: fixed;
top: 0;
}
π Behavior:
- Stays fixed on screen
- Does NOT move when scrolling
β Used for:
- navbar
- floating buttons
π 5. Sticky Position
div {
position: sticky;
top: 0;
}
π Behavior:
- Acts like relative first
- Becomes fixed when scrolling
β Used for sticky headers
π§ Position Summary
| Type | Behavior |
|---|---|
| static | normal flow |
| relative | move from original |
| absolute | free positioning |
| fixed | stuck on screen |
| sticky | hybrid (scroll effect) |
π§© Real Example
<div class="container">
<div class="box">Box</div>
</div>
.container {
position: relative;
height: 200px;
background: lightgray;
}
.box {
position: absolute;
top: 20px;
left: 20px;
background: red;
color: white;
padding: 10px;
}
π Fixed Navbar Example
.navbar {
position: fixed;
top: 0;
width: 100%;
background: black;
color: white;
}
β οΈ Common Mistakes
- Using absolute without parent β
- Confusing relative vs absolute β
- Overusing fixed elements β
- Breaking layout flow β
π― Pro Tip
π Modern layouts prefer:
- Flexbox (for structure)
- Grid (for layout)
- Position (only for special cases)
π§ͺ Mini Exercise
Create:
- A parent container
- A box inside it using absolute positioning
- A fixed navbar at top
- A sticky header that stays on scroll