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

การทับซ้อนองค์ประกอบด้วย Z-Index ใน CSS

คุณสมบัติ z-index ใน CSS ใช้ควบคุมลำดับชั้น (stacking order) ขององค์ประกอบที่ทับซ้อนกัน z-index สามารถเป็นค่าบวกหรือลบได้

หมายเหตุ: หากองค์ประกอบที่ทับซ้อนกันไม่ได้ระบุ z-index องค์ประกอบที่อยู่ทีหลังในโค้ด HTML จะแสดงด้านบน

ตัวอย่างที่ 1: Z-index แบบลบ (Negative)

<!DOCTYPE html>
<html>
<head>
  <style>
    p {
      margin: 0; position: absolute;
      top: 50%; left: 50%;
      transform: translate(-50%, -50%);
    }
    div {
      margin: auto; position: absolute;
      top: 0; left: 0; right: 0; bottom: 0;
    }
    div:first-child {
      background-color: orange; width: 270px; height: 120px; z-index: -2;
    }
    div:last-child {
      width: 250px; height: 100px; z-index: -1;
      background-color: turquoise;
    }
  </style>
</head>
<body>
  <div></div>
  <p>Fortran was originally developed by a team at IBM in 1957 for scientific calculations...................</p>
  <div></div>
</body>
</html>

ผลลัพธ์

การทับซ้อนองค์ประกอบด้วย Z-Index ใน CSS

ตัวอย่างที่ 2: ใช้ background-image แทน

<!DOCTYPE html>
<html>
<head>
  <style>
    p {
      background: url("https://www.tutorialspoint.com/tensorflow/images/tensorflow-mini-logo.jpg");
      background-origin: content-box; background-repeat: no-repeat;
      background-size: cover; box-shadow: 0 0 3px black;
      padding: 20px; background-origin: border-box;
    }
  </style>
</head>
<h2>Demo</h2>
<body>
  <p>This is demo text...</p>
</body>
</html>

ผลลัพธ์

การทับซ้อนองค์ประกอบด้วย Z-Index ใน CSS

Stacking Context (บริบทการซ้อน)

z-index ทำงานภายใน Stacking Context ซึ่งสร้างขึ้นเมื่อ:

  • Root element (<html>)
  • Position ไม่ใช่ static + z-index ไม่ใช่ auto
  • Opacity น้อยกว่า 1
  • Transform, Filter, Perspective ไม่ใช่ none
  • Will-change, Contain, Isolation properties

ลำดับ Stacking (จากด้านล่างขึ้นบน)

  1. Background/border ของ root
  2. Descendants ที่มี z-index ติดลบ
  3. Block-level normal flow
  4. Floats
  5. Inline-level normal flow
  6. Descendants ที่มี z-index: 0 หรือ auto
  7. Descendants ที่มี z-index บวก

เคล็ดลับ: ใช้ z-index เฉพาะเมื่อจำเป็น และจัดกลุ่ม stacking context ให้ชัดเจน