นี่เป็นตัวอย่างง่ายๆ แต่จะเป็นกุญแจสำคัญที่จะทำให้เข้าใจการ ซ้อนทับ ของเนื้อหาได้, มี DIV อยู่ 4 อัน ตามตัวอย่างด้านล่าง แต่จะต้องค่า z-index ให้มีความแตกต่างกันในส่วนของการจัดอันดับ การจัดเรียง
คุณจะเห็น DIV #2 (z-index: 2) อยู่บน DIV #3 (z-index: 1) เพราะว่า DIV ทั้งสองอัน มีการใช้ x-index ที่ต่างกัน ดังนั้นการกำหนดค่า z-index แบบนี้ทำให้รู้ว่า จะทำยังไงให้ element มันซ้อนทับกันได้
แต่แปลกใจไหมที่ DIV #2 (z-index: 2) อยู่บน DIV #4 (z-index: 10) ทั้งที่ z-index ของ DIV #2 จะน้อยกว่า DIV #4 เป็นเพราะว่า DIV#4 ได้รับการถ่ายทอด จะพูดง่ายๆ คือ มันอยู่ใน DIV #3 ซึ่ง มี z-index เป็น 1 ซึ่งมันน้อยกว่า DIV #2 ทำให้ DIV #4 ต้องรับอิทธิพล มาจาก DIV #3 ด้วย ที่ต้องอยู่ใต้ DIV #2 ที่มี z-index เป็น 2 ที่ค่ามากกว่า DIV #3
ดูการถ่ายทอดหรือการรับอิทธิพล จากตัวอย่างด้านล่างนี้ จะเข้าใจมากขึ้น
* root stacking context
o DIV #2 (z-index 2)
o DIV #3 (z-index 1)
+ DIV #4 (z-index 10)
Note:
* It is worth remembering that in general the HTML hierarchy is different from the stacking context hierarchy. In the stacking context hierarchy, elements that do not create a stacking context are collapsed on their parent.
Code ตัวอย่าง<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head><style type="text/css">
div { font: 12px Arial; }
span.bold { font-weight: bold; }
#div2 { z-index: 2; }
#div3 { z-index: 1; }
#div4 { z-index: 10; }
#div1,#div3 {
height: 80px;
position: relative;
border: 1px dashed #669966;
background-color: #ccffcc;
padding-left: 5px;
}
#div2 {
opacity: 0.8;
position: absolute;
width: 150px;
height: 200px;
top: 20px;
left: 170px;
border: 1px dashed #990000;
background-color: #ffdddd;
text-align: center;
}
#div4 {
opacity: 0.8;
position: absolute;
width: 200px;
height: 70px;
top: 65px;
left: 50px;
border: 1px dashed #000099;
background-color: #ddddff;
text-align: left;
padding-left: 10px;
}
</style></head>
<body>
<br />
<div id="div1">
<br /><span class="bold">DIV #1</span>
<br />position: relative;
<div id="div2">
<br /><span class="bold">DIV #2</span>
<br />position: absolute;
<br />z-index: 2;
</div>
</div>
<br />
<div id="div3">
<br /><span class="bold">DIV #3</span>
<br />position: relative;
<br />z-index: 1;
<div id="div4">
<br /><span class="bold">DIV #4</span>
<br />position: absolute;
<br />z-index: 10;
</div>
</div>
</body></html>
https://developer.mozilla.org/en/Understanding_CSS_z-index/Stacking_context_example_2