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

การเพิ่ม Multiple Backgrounds ด้วย CSS3

Multiple Backgrounds: ใส่หลายพื้นหลังใน Element เดียว

Property background-image รองรับหลายค่า คั่นด้วยจุลภาค (comma) เรียงจากบนลงล่าง (first = topmost) แต่ละ background ควบคุม background-position, repeat, size แยกได้

โค้ดตัวอย่าง

<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    div {
      background-image:
        url("https://pngimg.com/uploads/autumn_leaves/autumn_leaves_PNG3613.png"),
        url("https://i.picsum.photos/id/256/1200/300.jpg");
      background-position: left bottom, left top;
      background-repeat: repeat, repeat;
      padding: 15px;
    }
    p { font-size: 18px; }
  </style>
</head>
<body>
  <h1>Multiple Backgrounds using CSS</h1>
  <div>
    <h1>Some Sample Text</h1>
    <p>Lorem ipsum...</p>
  </div>
</body>
</html>

Syntax หลาย Background

.multi-bg {
  background-image: url(bg1.png), url(bg2.jpg), linear-gradient(...);
  background-position: center top, left bottom, 0 0;
  background-repeat: no-repeat, repeat-x, no-repeat;
  background-size: cover, auto, 100% 100%;
  background-color: #f0f0f0; /* สีท้ายสุด (bottom-most) */
}

Background Shorthand (แต่ละ layer คั่นด้วย comma)

.multi {
  background:
    url(icon.png) no-repeat 10px 10px / 32px 32px,  /* layer 1 */
    linear-gradient(45deg, #fff, #f0f0f0);           /* layer 2 */
}

ประยุกต์ใช้

  • Pattern + Photo background
  • Icon + Gradient background บนปุ่ม/การ์ด
  • Noise texture overlay บนสีทึบ
  • CSS-only decorative borders (gradient + pattern)

Browser Support

IE 9+, ทุก browser สมัยใหม่ – ใช้ได้จริงแล้ว