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

Absolute Positioning ใน CSS (ตำแหน่งแบบสัมบูรณ์)

เมื่อใช้ 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>

ผลลัพธ์

Absolute Positioning ใน CSS (ตำแหน่งแบบสัมบูรณ์)

คุณสมบัติสำคัญของ Absolute Positioning

  • ถูกนำออกจาก normal document flow (ไม่ครอบพื้นที่, ไม่ผลกระทบพี่น้อง)
  • จัดตำแหน่งสัมพันธ์กับ nearest positioned ancestor (พ่อที่มี position ไม่ใช่ static)
  • ถ้าไม่มี positioned ancestor จะอ้างอิงจาก initial containing block (html/body)
  • ใช้ top, right, bottom, left กำหนดตำแหน่งได้แม่นยำ
  • สร้าง stacking context ใหม่

กรณีใช้งานยอดนิยม

  • Modal, Dialog, Popup (fixed จริงๆ แต่มักใช้ absolute ใน container)
  • Tooltip, Dropdown menu
  • Badge/Notification count บนไอคอน
  • Image caption overlay
  • Loading spinner ตรงกลาง container

เทคนิค: จัดกลาง absolute element

/* จัดกลางแนวนอน + แนวตั้ง */
.centered {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

/* หรือใช้ margin auto (ต้องมี width/height) */
.centered {
  position: absolute;
  top: 0; right: 0; bottom: 0; left: 0;
  margin: auto;
  width: 300px; height: 200px;
}