เทคนิคการทำให้รูปภาพครอบคลุมเต็มหน้าจอ (Full-page Background) ใช้ background-size: cover และ height: 100% บน html/body
ตัวอย่างโค้ด
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> body, html { height: 100%; margin: 0; } .background { background-image: url("https://images.pexels.com/photos/1424246/pexels-photo-1424246.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=1000"); height: 100%; background-position: center; background-repeat: no-repeat; background-size: cover; } </style> </head> <body> <div class="background"></div> </body> </html>
คำอธิบาย CSS สำคัญ
- html, body { height: 100%; margin: 0; } - บังคับให้สูงเต็ม Viewport
- background-size: cover - ขยาย/ย่อรูปครอบคลุมพื้นที่ทั้งหมด (อาจครอป)
- background-position: center - จัดกึ่งกลางรูป
- background-repeat: no-repeat - ไม่ทILED
รูปแบบอื่น: Fixed Background (Parallax)
.background {
background-attachment: fixed; /* รูปคงที่ ขึ้นอยู่กับ Scroll */
}
ผลลัพธ์
รูปทิวทัศน์ครอบเต็มหน้าจอ ไม่มี Scrollbar (เพราะ height: 100% เท่านั้น)