สำหรับการจัดตำแหน่งองค์ประกอบ CSS มีวิธีการจัดตำแหน่งดังต่อไปนี้:
1. Relative Positioning (ตำแหน่งสัมพัทธ์)
เมื่อใช้ตำแหน่งสัมพัทธ์ องค์ประกอบจะถูกจัดตำแหน่งสัมพันธ์กับตำแหน่งปกติของมัน ใช้ position: relative
ตัวอย่าง
<!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>
ผลลัพธ์

2. Absolute Positioning (ตำแหน่งแบบสัมบูรณ์)
เมื่อใช้ตำแหน่งแบบสัมบูรณ์ องค์ประกอบจะถูกจัดตำแหน่งสัมพันธ์กับพ่อที่มีการจัดตำแหน่ง (positioned ancestor) ใกล้ที่สุด
ตัวอย่าง
<!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; } </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> <p>This is another demo text.</p> <p>This is demo text.</p> <p>This is demo text.</p> </body> </html>
ผลลัพธ์

3. Fixed Positioning (ตำแหน่งคงที่)
องค์ประกอบที่ตั้งค่า 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>
ผลลัพธ์

สรุปการใช้งาน
- static (ค่าเริ่มต้น) - ไม่ได้รับผลกระทบจาก top, bottom, left, right
- relative - สัมพันธ์กับตำแหน่งเดิม
- absolute - สัมพันธ์กับพ่อที่มี position ไม่ใช่ static
- fixed - สัมพันธ์กับ viewport (หน้าจอ)
- sticky - ผสมระหว่าง relative และ fixed