Home > Software design >  z-index not working with position relative
z-index not working with position relative

Time:08-20

I write css coded is the following lines. but not working z-index.

I want to know how I can make the z-index work while keeping the value of position as relative.

      #foo {
        position: relative;
        z-index: -1;
        width: 100%;
        height: 30%;
        background-color: lightblue;
      }

      #bar {
        width: 50%;
        height: 30%;
        background-color: lightpink;
      }

As far as I know, if you set the value of position to a non-static value, the z-index should work. Are there any other factors that affect the z-index?

Also if I change the value of position to absolute it works fine.

When position is relative

enter image description here

When position is absolute

enter image description here

Demo

https://codesandbox.io/s/heuristic-bose-bfetmj?file=/index.html

CodePudding user response:

  • everything is working as you need you can see I have added margin-bottom:-20px; to .foo so that you can se that in effect that .foo is behind .bar.
  • Understand that position won't take item out of flow, which will keep it at it's position. To see this in effect there must be some overlapping between two elements, than you can see the z-index in efffect.

html,
body {
  width: 100%;
  height: 100%;
}

#foo {
  position: relative;
  z-index: -1;
  width: 100%;
  height: 30%;
  background-color: lightblue;
  margin-bottom: -20px;
}

#bar {
  width: 50%;
  height: 30%;
  background-color: lightpink;
}
<div id="foo">Foo</div>
<div id="bar">Bar</div>

  • Related