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

CSS Z-Index: จัดลำดับชั้น元素บนแกน Z (Stacking Context)

ออกแบบ layout ด้วย CSS มักจัดตำแหน่ง元素 ซ้าย/ขวา บน/ล่าง z-index ให้เลื่อน元素บน แกน Z (มิติที่ 3) แบบซ้อนทับ (stacking)

ค่าของ z-index

z-index: auto; z-index: -1; z-index: 9999;

รับ auto หรือ integer (ลบ/บวกได้)

เงื่อนไขสำคัญ: ต้องมี position เป็น relative, absolute หรือ fixed ถ้าไม่มี position จะเหมือน z-index: auto ไม่สร้าง stacking context

ตัวอย่าง: วางหนูแกมูบนทะเลสาบและกาแฟ

2 ตัวหนูแกมู (Cuy) — ตัวที่ 1 วางในทะเลสาบ, ตัวที่ 2 วางบนถ้วยกาแฟ

โดยไม่มี positioning: ภาพทับซ้อนกันไม่เป็นระเบียบ

เพิ่ม positioning และ z-index:

img.cuy.one { position: absolute; z-index: 1; }  /* บนทะเลสาบ */
img.cuy.two { position: absolute; width: 160px; padding: 100px; z-index: 1; }  /* บนกาแฟ */

padding ใช้จัดตำแหน่งที่แน่นอน width ปรับขนาด

ข้อควรระวังสำคัญ

  1. ต้องมี position (relative/absolute/fixed) ไม่เช่นนั้น z-index ไม่ทำงาน
  2. ใช้กับ sibling elements (元素同级) — หาก nested ลึก z-index อาจทำงานไม่เหมือนคาด

สรุป

z-index เปิดโอกาส layout น่าสนใจ ต้องมี position เสมอ ลองลบ position ใน Codepen ดูผลกับตัวเอง — ใช้กับ sibling elements ให้ผลดีที่สุด