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

วิธีสร้าง Footer ติดด้านล่าง (Fixed/Sticky Footer) ด้วย CSS

Fixed Footer: ค้างอยู่ขอบล่างจอตลอดเวลา

ใช้ position: fixed กับ bottom: 0; left: 0; width: 100% ทำให้ Footer อยู่ตำแหน่งเดิมตลอดแม้จะ scroll เนื้อหาเหนือ

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

<!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; }
    .footer {
      font-size: 20px;
      position: fixed;
      left: 0; bottom: 0; width: 100%;
      background-color: rgb(50, 6, 100);
      color: white; text-align: center;
    }
  </style>
</head>
<body>
  <h1>ตัวอย่าง Fixed/Sticky Footer</h1>
  <div class="footer"><p>All rights reserved ©</p></div>
</body>
</html>

จุดสังเกต

  • Footer จะทับเนื้อหาเมื่อ scroll ถึงท้าย – ควรเพิ่ม padding-bottom ให้ body/container เท่าความสูง footer
  • บนมือถืออาจบัง UI ของเบราว์เซอร์ (address bar) – ทดสอบจริงสำคัญ
  • ใช้ z-index หากมีองค์ประกอบ fixed อื่น (chat widget, cookie banner)

ตัวเลือก: Sticky Footer (ไม่ใช่ Fixed)

หากต้องการ Footer อยู่ล่างสุดของ *เนื้อหา* (ไม่ค้างจอ) ใช้ Flexbox:

body { display: flex; flex-direction: column; min-height: 100vh; }
main { flex: 1; } /* เนื้อหาหลักขยายเต็มพื้นที่ */
footer { /* ไม่ต้อง fixed */ }

วิธีนี้ Footer จะอยู่ล่างสุดถ้าเนื้อหาน้อย และถูกผลักลงไปถ้าเนื้อหาเยอะ