คุณสมบัติพื้นหลังหลัก 2 ตัวคือ background-position (ตำแหน่งเริ่มต้น) และ background-repeat (การทำซ้ำ)
1. background-position
กำหนดตำแหน่งเริ่มต้นของ background image
ค่าที่ใช้ได้:
- Keyword:
top,bottom,left,right,center - Percentage:
50% 50%(center) - Length:
20px 30px(จาก top-left) - ผสม:
right 20px bottom 10px(จากขอบที่ระบุ)
ตัวอย่าง background-position
<!DOCTYPE html> <html> <head> <style> body { background-image: url("https://www.tutorialspoint.com/images/Swift.png"); background-repeat: no-repeat; background-attachment: fixed; color: blue; background-position: left center; } .demo { text-decoration: overline underline; } </style> </head> <body> <h1>Details</h1> <p class="demo">Examination Center near ABC College.</p> <p class="demo2">Exam begins at 9AM.</p> </body> </html>
2. background-repeat
กำหนดวิธีการทำซ้ำของ background image
ค่าที่ใช้ได้:
background-repeat: repeat | repeat-x | repeat-y | no-repeat | space | round | initial | inherit;
| ค่า | คำอธิบาย |
|---|---|
repeat | ทำซ้ำทั้งแนวนอนและแนวตั้ง (ค่าเริ่มต้น) |
repeat-x | ทำซ้ำเฉพาะแนวนอน |
repeat-y | ทำซ้ำเฉพาะแนวตั้ง |
no-repeat | ไม่ทำซ้ำ แสดงครั้งเดียว |
space | ทำซ้ำและกระจายเท่าๆ กัน ไม่ตัดภาพ |
round | ทำซ้ำและปรับขนาดให้พอดีพื้นที่ ไม่ตัดภาพ |
ตัวอย่าง background-repeat
<!DOCTYPE html> <html> <head> <style> body { background-image: url("https://www.tutorialspoint.com/images/Swift.png"); background-repeat: repeat-x; background-color: blue; color: white; } .demo { text-decoration: overline underline; } </style> </head> <body> <h1>Details</h1> <p class="demo">Examination Center near ABC College.</p> <p class="demo2">Exam begins at 9AM.</p> </body> </html>
คำอธิบายเพิ่มเติม
ตัวอย่างแรก: background-position: left center วางภาพด้านซ้ายกึ่งกลางแนวตั้ง background-attachment: fixed ทำให้ภาพคงที่ตอน scroll
ตัวอย่างที่สอง: repeat-x ทำซ้ำแนวนอน เหมาะสำหรับ header/footer pattern
รูปแบบสองค่า (Two-value syntax):
background-repeat: repeat-x no-repeat; /* horizontal, vertical */ background-repeat: round space; /* horizontal round, vertical space */
Multiple Backgrounds:
background-image: url(a.png), url(b.png); background-position: top left, bottom right; background-repeat: no-repeat, repeat-x;