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

วิธีย่อขนาด Header ขณะ Scroll ด้วย CSS และ JavaScript

Shrink Header on Scroll: ลดขนาด Header เมื่อเลื่อนลง

ใช้ JavaScript detect scroll position (scrollTop > 50) แล้วเปลี่ยน font-size (หรือ padding/height) ของ fixed header พร้อม CSS transition ทำให้เล็กลงนุ่มนวล

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

<!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: 0; padding: 0; height: 150vh; }
    .header {
      position: fixed; top: 0; width: 100%;
      background-color: rgb(52, 21, 110); color: white;
      padding: 50px; font-size: 40px; transition: 0.8s;
    }
  </style>
</head>
<body>
  <div class="header">Header Text</div>
  <p style="font-size: 35px;">Lorem ipsum...</p>
  <script>
    window.onscroll = function() { resizeHeader(); };
    function resizeHeader() {
      if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
        document.querySelector(".header").style.fontSize = "20px";
      } else {
        document.querySelector(".header").style.fontSize = "40px";
      }
    }
  </script>
</body>
</html>

ปรับปรุงให้ทันสมัยและประสิทธิภาพดีกว่า

  1. ใช้ Class แทน Inline Style – แยก concerns, ง่ายต่อ maintenance
    .header.shrunk { font-size: 20px; padding: 20px; }
  2. ใช้ IntersectionObserver หรือ Passive Event Listener – ไม่บล็อก main thread
    window.addEventListener('scroll', () => {
      header.classList.toggle('shrunk', window.scrollY > 50);
    }, { passive: true });
  3. CSS Custom Properties – ควบคุมหลายค่า (height, padding, font-size) พร้อมกัน
    .header { --header-h: 100px; height: var(--header-h); transition: --header-h 0.3s; }
    .header.shrunk { --header-h: 60px; }

UX Tips

  • Header ควรมี z-index สูงพอครับเนื้อหา
  • เพิ่ม logo/navigation ที่ปรับขนาดพร้อมกัน
  • พิจารณา backdrop-filter: blur(10px) ให้ header โปร่งแสงสวยงาม