0

How does z-index really work?


 <div class="picture">
      <img src="img/japan1.png" alt="">
      <img src="img/japan2.png" alt="">
      <img src="img/japan3.png" alt="">
      <img src="img/japan4.png" alt="">
      <img src="img/japan5.png" alt="">
  </div>

*{
    box-sizing: border-box;
}

.picture{

    background-color:rgb(189, 178, 155);
    height: 540px;
    width:960px;
    margin: 100px auto;
    position: relative;
    overflow: hidden;
    z-index:-1;


}
img
{
    width:960px;
    height:540px;
    position: relative;
    z-index: 0;

}


img:nth-child(1){

    top:50px;
    z-index:2;

}
img:nth-child(2){

    top:125px;
    z-index:10;

}
 img:nth-child(3){
    top:186px;
    z-index:6;
 }

i expected z-index will work, but i can see only see first child and background color on the screen. What is happening? With position absolute on img its working well.enter image description here

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
  • you need position:absolute not relative for the image (in your case everything is overflowing and only the first one is within the parent element – Temani Afif May 23 '19 at 21:54
  • If i correctly understand : relative parent cannot be contener for relative childs, but can be for absolute childs? i mean positioning in reference to parent. – Gustavo Fring May 23 '19 at 22:02
  • no they can, what you are missing is the meaning of position:relative which will consider the intial place of the element as the reference unlike the position:absolute and here you need to stack image so you need position:absolute (here is a good answer to illustrate https://stackoverflow.com/a/42720659/8620333 ) – Temani Afif May 23 '19 at 22:04

0 Answers0