สร้างเอฟเฟกต์ Parallax/Background Change เมื่อ Scroll โดยใช้หลาย Section ที่มี Background Image ต่างกัน คงที่ตำแหน่ง (background-attachment: fixed ไม่ได้ใช้ในตัวอย่าง แต่ใช้ height คงที่)
ตัวอย่างโค้ด
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1> <style> body, html { height: 100%; margin: 0; font-family: Arial, Helvetica, sans-serif; } * { box-sizing: border-box; } div { height: 40%; background-position: center; background-repeat: no-repeat; background-size: cover; } .image1 { background-image: url("https://i.picsum.photos/id/827/400/400.jpg"); } .image2 { background-image: url("https://i.picsum.photos/id/817/400/400.jpg"); } .image3 { background-image: url("https://i.picsum.photos/id/811/400/400.jpg"); } .image4 { background-image: url("https://i.picsum.photos/id/871/400/400.jpg"); } .image5 { background-image: url("https://i.picsum.photos/id/471/400/400.jpg"); } .image6 { background-image: url("https://i.picsum.photos/id/271/400/400.jpg"); } h1{ position:fixed; top:10%; left: 40%; background-color: rgba(0, 0, 0, 0.527); padding: 40px; color: white; } </style> </head> <body> <div class="image1"></div> <div class="image2"></div> <div class="image3"></div> <div class="image4"></div> <div class="image5"></div> <div class="image6"></div> <h1>Fixed Text</h1> </body> </body> </html>
การทำงาน
- 6
<div>ติดกัน แต่ละอันheight: 40%รวม 240% VH - แต่ละ Div มี Background Image ต่างกัน
background-size: cover - เลื่อนหน้าจู -> เห็นรูปเปลี่ยนไปเรื่อยๆ
h1 { position: fixed; } - ข้อความ "Fixed Text" คงที่บนหน้าจอตลอด
True Parallax (background-attachment: fixed)
.parallax {
background-attachment: fixed;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
height: 100vh;
}
รูปจะ "ค้าง" ไว้ ขณะเนื้อหาเลื่อนผ่าน -> เอฟเฟกต์ลึก (Depth)
หมายเหตุ
- ตัวอย่างมี
</body>ซ้ำ 2 ครั้ง (Typo) - รูปจาก picsum ID ต่างกัน สุ่มได้ทุกครั้ง
- บน Mobile
background-attachment: fixedมักมี Bug/Performance Issue
ผลลัพธ์
หน้าเว็บยาว 6 Section รูปเปลี่ยนติดกัน ข้อความ "Fixed Text" คงที่ตรงกลางบนสุด