การจัดตำแหน่งแบบ Relative (position: relative) วาง element ตามปกติใน document flow แล้วค่อยเลื่อนจากตำแหน่งเดิมด้วย top/right/bottom/left
ตัวอย่างโค้ด
<!DOCTYPE html> <html> <head> <style> div.demo { position: relative; color: white; background-color: orange; border: 2px dashed blue; left: 50px; } </style> </head> <body> <h2>Demo Heading</h2> <p>This is demo text.</p> <p>This is demo text.</p> <div class="demo"> position: relative; </div> <p>This is another demo text.</p> </body> </html>
คำอธิบาย
Element ที่มี position: relative และ left: 50px จะเลื่อนไปขวา 50px จากตำแหน่งปกติ แต่ พื้นที่เดิมยังคงถูกครอง (element ถัดมาไม่ขึ้นแทนที่)
ลักษณะสำคัญของ Relative Positioning:
| ลักษณะ | คำอธิบาย |
|---|---|
| อยู่ใน document flow | ยังครองพื้นที่เดิม ส่งผลต่อ layout อื่นๆ |
| จุดอ้างอิง | ตำแหน่งปกติของตัวเอง (ไม่ใช่ parent) |
| z-index ทำงาน | สามารถควบคุมลำดับชั้นได้ |
| เป็น containing block | สำหรับ child ที่ position: absolute |
กรณีใช้งานทั่วไป:
- ปรับตำแหน่งเล็กน้อย (micro-adjustment)
- สร้าง anchor สำหรับ absolute child
- Animation/transition ที่ต้องการกลับตำแหน่งเดิม
- Tooltip, dropdown trigger
เปรียบเทียบ Position Types:
| Type | ใน Flow? | จุดอ้างอิง | ครองพื้นที่? |
|---|---|---|---|
| static | ใช่ | - | ใช่ |
| relative | ใช่ | ตัวเอง | ใช่ |
| absolute | ไม่ | relative ancestor | ไม่ |
| fixed | ไม่ | viewport | ไม่ |
| sticky | ใช่* | viewport/ancestor | ใช่* |