Element ที่ตั้งค่า position: fixed จะคงที่อยู่ที่ตำแหน่งเดิมแม้จะเลื่อนหน้าเว็บ (scroll) ไป
ตัวอย่างโค้ด
<!DOCTYPE html> <html> <head> <style> div.demo1 { position: relative; color: white; background-color: orange; border: 2px dashed blue; width: 600px; height: 200px; } div.demo2 { position: absolute; color: white; background-color: orange; border: 2px dashed blue; top: 50px; right: 0; width: 300px; height: 100px; } div.demo3 { position: fixed; bottom: 0; right: 20px; width: 500px; border: 3px solid orange; color: blue; } </style> </head> <body> <h2>Demo Heading</h2> <p>This is demo text.</p> <p>This is demo text.</p> <p>This is demo text.</p> <p>This is demo text.</p> <div class="demo1">position: relative; <div class="demo2"> position: absolute; </div> <div class="demo3"> position: fixed; </div> </div> <p>This is another demo text.</p> </body> </html>
คำอธิบาย
ตัวอย่างเปรียบเทียบ 3 ประเภทของ positioning:
- Relative (demo1) - จัดตำแหน่งตามปกติ แล้วค่อยเลื่อนจากตำแหน่งเดิม
- Absolute (demo2) - จัดตำแหน่งตาม ancestor ใกล้สุดที่มี position ไม่ใช่ static (ในที่นี้คือ demo1)
- Fixed (demo3) - จัดตำแหน่งตาม viewport (หน้าจอ) คงที่ตลอดเวลาแม้ scroll
การใช้งานจริงของ Fixed Positioning:
- Navigation bar ที่ติดอยู่บนสุด (sticky nav)
- ปุ่ม "Back to top" ที่มุมล่างขวา
- Chat widget / Floating action button
- Cookie consent banner
- Modal overlay backdrop
คุณสมบัติที่ใช้กับ Fixed:
ใช้ top, right, bottom, left กำหนดตำแหน่งจากขอบ viewport และ z-index ควบคุมลำดับชั้น