🎨
Layout and Positioning
Beginner
80 XP
30 min
Lesson Content
Layout and Positioning
CSS positioning allows you to control where elements appear on the page. Understanding different positioning types is crucial for creating complex layouts.
Position Types
- static: Default positioning, elements flow normally
- relative: Positioned relative to its normal position
- absolute: Positioned relative to nearest positioned ancestor
- fixed: Positioned relative to viewport, stays in place when scrolling
- sticky: Acts like relative until scrolled, then becomes fixed
Positioning Properties
- top, right, bottom, left: Offset values (px, %, em)
- z-index: Controls stacking order
Example
.container {
position: relative;
}
.box {
position: absolute;
top: 20px;
right: 10px;
}Example Code
Use relative and absolute positioning to place elements
<!DOCTYPE html>
<html><head><style>
.container {
position: relative;
width: 200px;
height: 200px;
background: #dbeafe;
border: 2px solid #3b82f6;
}
.box {
width: 80px;
height: 80px;
background: #60a5fa;
position: absolute;
top: 20px;
left: 20px;
}
.inner {
position: absolute;
right: 0;
top: 0;
background: #fbbf24;
padding: 5px;
width: 30px;
height: 30px;
}
</style></head><body>
<div class="container">
<div class="box">
<div class="inner">X</div>
</div>
</div>
</body></html>Expected Output:
X
Study Tips
- •Read the theory content thoroughly before practicing
- •Review the example code to understand key concepts
- •Proceed to the Practice tab when you're ready to code