Parallax Effect: พื้นหลังเลื่อนช้ากว่าเนื้อหา สร้างความลึก
ใช้ background-attachment: fixed บนพื้นหลังรูปภาพ ทำให้ภาพคงที่ตำแหน่งขณะ scroll เนื้อหาเลื่อนผ่าน สร้างความรู้สึก 3D/ความลึก
โค้ดตัวอย่าง
<!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; height: 100vh; margin: 0; padding: 0; }
.parallax {
background-image: url("https://i.picsum.photos/id/250/800/800.jpg");
height: 100%; background-attachment: fixed;
background-position: center; background-repeat: no-repeat; background-size: cover;
}
.parallaxText { font-size: 20px; height: 100%; }
</style>
</head>
<body>
<div class="parallax"></div>
<div class="parallaxText">
<h1>Some random text</h1><h1>Some random text</h1>
<p>Lorem ipsum dolor sit amet...</p>
</div>
<div class="parallax"></div>
</body>
</html>
จุดสำคัญ
background-attachment: fixed – หัวใจของ parallax แบบ CSS onlybackground-size: cover– ครอบเต็มพื้นที่ คงสัดส่วน- ต้องมีเนื้อหายาวพอให้ scroll (height > 100vh)
ข้อจำกัด & แก้ไข
- Mobile/iOS Safari:
background-attachment: fixedไม่ทำงาน/ลืม – ใช้ JavaScript (IntersectionObserver + transform) แทน - Performance: รูปใหญ่หลายชั้นอาจทำให้ scroll ลั่น – ใช้
will-change: transformหรือลดจำนวน layer - Accessibility: เพิ่ม
@media (prefers-reduced-motion: reduce) { .parallax { background-attachment: scroll; } }
ทางเลือกทันสมัย
ใช้ transform: translate3d(0, y, 0) ควบคุมด้วย JS (scroll event หรือ IntersectionObserver) ควบคุมความเร็วแต่ละ layer ได้แม่นยำ (speed factor) และทำงานบน mobile ได้