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

วิธีสร้าง Sticky Image (รูปติดตาม Scroll) ด้วย CSS

ใช้ CSS position: sticky; top: 0; ทำให้รูปภาพ "ติด" อยู่ที่ตำแหน่งเมื่อ Scroll จนถึงขอบบน แล้วคงที่ไว้จน Scroll ผ่านไป

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

<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> img {    position: sticky;    top: 0;    width: 300px;    height: 300px; } </style> </head> <body> <h1>Some header text</h1> <img src="https://i.picsum.photos/id/721/400/400.jpg"> <h1>Some header text</h1> <h1>Some header text</h1> <h1>Some header text</h1> <p style="font-size: 40px;">Lorem ipsum dolor sit amet consectetur adipisicing elit. Fugiat odio ratione officia quod qui blanditiis animi! Repudiandae culpa recusandae dolor id soluta porro commodi quidem, incidunt voluptatum vitae similique nesciunt obcaecati odit enim repellat doloribus. Explicabo quisquam in beatae earum?</p> </body> </html>

Position: Sticky คืออะไร?

  • ผสมผสานระหว่าง relative และ fixed
  • ปกติ: อยู่ตาม Flow ปกติ (relative)
  • เมื่อ Scroll จน Element จะหลุดออก Viewport -> กลายเป็น fixed ติดขอบ (top: 0)
  • เมื่อ Scroll กลับมา -> กลับเป็น Relative อัตโนมัติ

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

  1. Parent ต้องไม่มี overflow: hidden/auto/scroll (ยกเว้น body)
  2. ต้องระบุ Offset: top: 0 (หรือ bottom/left/right)
  3. Element ต้องมีความสูงน้อยกว่า Viewport

กรณีใช้งาน

  • Product Image ใน Detail Page (ติดข้างคำอธิบาย)
  • Sidebar Widget (Sticky Sidebar)
  • Table Header (Sticky Header)
  • Article Featured Image

ผลลัพธ์

รูป 300x300 เริ่มต้นอยู่ล่าง Header แรก Scroll ลง -> รูปติดบนสุด คงที่ ข้อความเลื่อนผ่านใต้รูป