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

การตั้งค่าตำแหน่งพื้นหลังด้วย CSS (background-position)

ตำแหน่งพื้นหลัง (Background position) ใช้สำหรับกำหนดตำแหน่งเริ่มต้นของภาพพื้นหลัง ใช้คุณสมบัติ background-position

ตัวอย่างที่ 1: left center

<!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>

ผลลัพธ์

การตั้งค่าตำแหน่งพื้นหลังด้วย CSS (background-position)

ตัวอย่างที่ 2: 50% 50% (กึ่งกลาง)

<!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: 50% 50%; } </style> </head> <body> <h1>Details</h1> <p>Examination Center near ABC College.</p> <p>Exam begins at 9AM.</p> </body> </html>

ผลลัพธ์

การตั้งค่าตำแหน่งพื้นหลังด้วย CSS (background-position)

ไวยากรณ์และค่าที่ใช้ได้

/* คีย์เวิร์ด */
background-position: left top;
background-position: center center;
background-position: right bottom;

/* เปอร์เซ็นต์ (0% 0% = มุมซ้ายบน, 100% 100% = มุมขวาล่าง) */
background-position: 50% 50%;  /* กึ่งกลาง */
background-position: 20% 80%;

/* ความยาว (px, em, rem, cm...) */
background-position: 50px 100px;
background-position: 2em 3em;

/* ผสมได้ */
background-position: left 20px bottom 10px; /* CSS Background Level 4 */

คำอธิบาย % vs px

  • px/em/rem - วัดจากขอบซ้ายบนของ container ไปยังขอบซ้ายบนของภาพ
  • % - จุดที่ % ของภาพ จะตรงกับจุดที่ % ของ container (ยากกว่าที่คิด)
  • 50% 50% = จุดกึ่งกลางภาพ ตรง กึ่งกลาง container (จัดกลางได้สมบูรณ์)

คุณสมบัติพื้นหลังที่เกี่ยวข้อง

background-image: url(...);
background-repeat: no-repeat;
background-attachment: fixed | scroll | local;
background-size: cover | contain | 100% 100%;
background-origin: padding-box | border-box | content-box;
background-clip: border-box | padding-box | content-box; /* ตัดพื้นหลัง */