Friday 5 December 2014

Aturan z-index

Saat kita membuat beberapa elemen HTML dengan z-index yang berbeda-beda,
kita berpikir hasilnya akan muncul mulai dari elemen z-index terkecil di paling bawah, kemudian diatasnya elemen z-index lebih besar dan seterusnya.

Tapi ternyata itu tidak terjadi, kenapa?

Saya akan membahas alasan hal tersebut tidak terjadi.




Saya beri contoh terdapat HTML seperti berikut.

.container{
  padding: 50px;
}
.box{
  width: 50px;
  height: 50px;
  position: fixed;
}

.green{
  background: #4CAF50;
  z-index: 1;
}

.red{
  background: #F44336;
  z-index: 3;
}
.lime{
  background: #CDDC39;
  z-index: 2;
  top: 50px;
  left: 20px;
}

/*
If you see the "z-index" of all the boxes,
you probably would expect that 
it will show up as .red -> .lime -> .green

But, if you see the result,
it is show up as .lime -> .red -> .green

Why is that?

Because,

.red is nested in .green. 

.red will be on the top of .green since the z-index is larger, but 

.lime will be on the top of .red, because z-index of .lime is larger than the parent of .red.

Conclusion:

the rule of z-index are
siblings come first, parent and children come after. 
*/


/*
How to make them show up as .red -> .lime -> .green?

Easy, move .red so that three of them became sibling

*/




See the Pen Rule of z-index by pras abdilah (@pras-abdilah) on CodePen.

Jika dilihat dari z-index ketiga box tersebut, mungkin Anda akan mengira akan tampil .red -> .lime -> .green.

Tapi ternyata hasilnya adalah .lime -> .red -> .green.

Kenapa?


.red berada daam .green,
sehingga .red akan tampil diatas .green.

Akan tetapi,
.lime akan tetap di atas .red walau z-indexnya kalah besar dari .red,
karena z-index dari parent .red, yaitu .green adalah lebih kecil dari z-index .lime.

Untuk membuatnya tampil menjadi .red -> .lime -> .green, Anda harus memindah .red sehingga menjadi sibling dari kedua elemen lainnya.


Kesimpulan 


Aturan z-index adalah:
sibling/ elemen saudara lebih didahulukan daripada parent and children/ induk dan turunan.
Sebesar apapun z-index suatu elemen, bila z-index induk/parent nya kecil, tak akan tampil diatas elemen yang z-indexnya lebih besar dari z-index induk/parent elemen tersebut.

--

Jangan lupa, z-index hanya berlaku di position: relative, absolute, atau fixed.