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

วิธีสร้างองค์ประกอบติดติด (Sticky Element) ด้วย CSS

Position Sticky: ติดตอน Scroll ถึงจุดที่กำหนด

position: sticky เป็น hybrid ของ relative และ fixed – ปกติอยู่ใน flow ปกติ แต่เมื่อ scroll จนถึง threshold (top, bottom, left, right) จะกลายเป็น fixed ค้างอยู่ที่ตำแหน่งนั้น

โค้ดตัวอย่าง

<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <style>
    body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
      margin: 0px; padding: 0px;
      height: 150vh; /* สร้าง scrollbar */
    }
    div.sticky {
      position: sticky;
      top: 0;
      background-color: rgb(52, 21, 110);
      color: white;
      padding: 50px;
      font-size: 20px;
    }
  </style>
</head>
<body>
  <h1>ตัวอย่าง Sticky Element</h1>
  <h2>Random Header Text</h2>
  <h2>Randorm Header Text</h2>
  <div class="sticky">Sticky Element</div>
  <p style="font-size: 35px;">Lorem ipsum dolor sit amet...</p>
</body>
</html>

เงื่อนไขการทำงาน

  • ต้องกำหนด อย่างน้อยหนึ่งค่า จาก top, bottom, left, right
  • Parent ต้องไม่มี overflow: hidden/scroll/auto (ยกเว้น body)
  • รองรับบราว์เซอร์สมัยใหม่ทั้งหมด (IE ต้องใช้ prefix -webkit-sticky)

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

  • Sticky Header / Navbar
  • Sidebar ค้างขณะอ่านบทความยาว
  • Table header ค้างขณะเลื่อนข้อมูล
  • ปุ่ม "Back to Top" หรือ CTA