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

รวมคุณสมบัติพื้นหลังทั้งหมดด้วย CSS background shorthand


คุณสมบัติ background (Shorthand)

คุณสมบัติ background เป็น shorthand ที่รวมคุณสมบัติพื้นหลังทั้งหมดไว้ในบรรทัดเดียว ช่วยลดโค้ดและเพิ่มความอ่านง่าย

ลำดับค่าที่แนะนำ

background: <color> <image> <repeat> <attachment> <position>;
คุณสมบัติย่อยคำอธิบาย
background-colorสีพื้นหลัง
background-imageภาพพื้นหลัง (url())
background-repeatการทำซ้ำ: repeat, no-repeat, repeat-x, repeat-y
background-attachmentการเลื่อน: scroll, fixed, local
background-positionตำแหน่ง: top, bottom, left, right, center, หรือเปอร์เซ็นต์/พิกเซล

ตัวอย่างการใช้งาน

<html>
<head>
  <style>
    #demo {
      background: lightblue url("https://www.tutorialspoint.com/css/images/css-mini-logo.jpg") no-repeat fixed top;
    }
  </style>
</head>
<body>
  <div id="demo">
    <h1>www.tutorialspoint.com</h1>
    <p>พื้นหลังสีฟ้าอ่อน พร้อมโลโก้ ตรงกลางบน ไม่ทำซ้ำ คงที่ตอนเลื่อนหน้าจอ...</p>
  </div>
</body>
</html>

หมายเหตุสำคัญ

  • ลำดับค่าสามารถสลับได้บ้าง แต่แนะนำให้ปฏิบัติตามมาตรฐาน
  • หากไม่ระบุค่าใดค่าจะใช้ค่าเริ่มต้น (initial value)
  • สามารถใช้ background-size และ background-clip ได้ใน syntax แบบใหม่ (CSS3+)