ปัญหา CSS Sticky

Published on
CSS
Discord

วันนี้นั่งปรับแต่ง CSS โดยจะลองใช้ position: sticky แต่แอบสงสัยว่า ทำไมบาง element มันก็ไม่ยอม sticky เวลาเลื่อน scroll ลงแฮะ ลองแก้ และลองหาข้อมูล พบว่า มีหลายๆข้อเลยที่มีโอกาสทำให้ css sticky ของเราไม่ทำงาน เช่น

  • ต้องใส่ height ให้ parent ด้วย
  • ถ้า parent มีการกำหนด overflow ไว้ sticky จะไม่ทำงาน
  • ต้องกำหนด top, right, bottom, left ให้มันด้วย อย่างใดอย่างหนึ่ง
  • IE 11 หมดโอกาส เพราะไม่ support

จาก MDN เขียนอธิบายไว้ แบบนี้

The element is positioned according to the normal flow of the document, and then offset relative to its nearest scrolling ancestor and containing block (nearest block-level ancestor), including table-related elements, based on the values of top, right, bottom, and left. The offset does not affect the position of any other elements.

ตัวอย่าง Sticky

.sticky {
  position: 'sticky';
  top: '10px';
}
Buy Me A Coffee
Authors
Discord