0

I have written a simple code with a main box containing two smaller boxes inside.

I have set the position of the smaller boxes to absolute, in order to set their positioning according to their parent.

What i would like to do is to bring the son2 div in front, since now is hidden by sondiv

I tried the z-index property but (as i expected) my element gets under the parent element, and not under the small blue box

#parent {
  position: absolute;
  background-color: red;
  width: 100px;
  height: 100px;
  margin-top: 200px;
  margin-left: 200px;
}

#son2 {
  position: absolute;
  background-color: green;
  width: 50px;
  height: 50px;
  margin-top: 20px;
}

#son {
  position: absolute;
  background-color: blue;
  width: 50px;
  height: 50px;
  margin-top: 10px;
}
<div id="parent">
  <div id="son2"></div>
  <div id="son"></div>
</div>

Demo on Codepen: https://codepen.io/mattiasu96/pen/KbpyNQ

Mattia Surricchio
  • 1,362
  • 2
  • 21
  • 49
  • 1
    z-index:0 to the parent then you can play with z-index on the child like you want and they won't go below parent – Temani Afif Dec 11 '18 at 22:12
  • @TemaniAfif It works! But why do i have to set the parent to z-index:0? https://www.w3schools.com/cssref/pr_pos_z-index.asp I've read the explanation in here, but i don't get why now it works doing as you suggested – Mattia Surricchio Dec 11 '18 at 22:16
  • 1
    z-index:0 will create a stacking context and will force all the child to belong inside it and never get out. Check this : https://stackoverflow.com/questions/51603351/i-have-position-but-z-index-is-not-working/51603436#51603436 (it's the opposite of what you want but it explain the stacking context issue) .. another one :https://stackoverflow.com/questions/52074761/css-z-index-issue-with-nested-elements/52074840#52074840 – Temani Afif Dec 11 '18 at 22:21

1 Answers1

1

Tiny change (just add z-index: 1; to son2). By the way you don't want to set position: absolute for the parent unless you need to change its position from the natural one as well, otherwise go with position: relative so that it's rendered normally but the absolute positioned children still behave as intended.

I've removed the margins from the parent just so you don't have to scroll in the snippet in order to see the divs, but no difference if you need that in your original problem.

#parent {
  position: relative;
  background-color: red;
  width: 100px;
  height: 100px;
}

#son2 {
  position: absolute;
  background-color: green;
  width: 50px;
  height: 50px;
  margin-top: 20px;
  z-index: 1;
}

#son {
  position: absolute;
  background-color: blue;
  width: 50px;
  height: 50px;
  margin-top: 10px;
}
<div id="parent">
  <div id="son2"></div>
  <div id="son"></div>
</div>
Herick
  • 1,687
  • 1
  • 14
  • 19