Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> CSS

การจัดตำแหน่งแบบ Relative (Relative Positioning) ใน CSS

การจัดตำแหน่งแบบ 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ใช่*