0

I'm facing an issue where I need to position the .arrow element on top of all layers within my HTML structure without making any changes to the structure itself. Despite setting z-index values, the .arrow element isn't displaying as intended. I've included the relevant HTML and CSS code below for reference.

body {
  display: flex;
  justify-content: center;
}

.container {
  position: relative;
  width: 400px;
  height: 400px;
  background-color: red;
}

.wrapper {
  position: relative;
  background-color: green;
  width: 200px;
  height: 200px;
  z-index: 2;
}

.arrow {
  top: 0;
  left: 0;
  position: absolute;
  background-color: yellow;
  width: 50px;
  height: 200px;
  z-index: 3;
}

.background {
  top: 0;
  left: 0;
  position: absolute;
  background-color: blue;
  width: 100px;
  height: 200px;
  z-index: 2;
}
<div class="container">
  <div class="wrapper">
    <div class="arrow"></div> 
  </div>
  <div class="background"></div>
</div>

I've tried adjusting the z-index values to control the stacking order, but the .arrow element isn't consistently displaying above all layers. Is there a solution to achieve this stacking order without modifying the existing HTML structure? Any insights or suggestions would be greatly appreciated.

Stairss
  • 176
  • 1
  • 14

1 Answers1

1

You should look at MDN page for Stacking Contexts

I won't go into the details, this is a complex topic, but the summary of it is that when a stacking context is created (in your case by having you .wrapper positionned and with a z-index), all the child element's z-index will be relative to the parent's z-index. It means that by setting z-index: 3; for your arrow it is not considered in an absolute manner, global to the page, but relative to its parent with z-index: 2;

You already see in your snippet that the .background is already on top of the .wrapper. It means that it will be also on top of its children.

You can lower the z-index for .background to 1 for example so that it doesn't go on top of .wrapper to start with.

body {
  display: flex;
  justify-content: center;
}

.container {
  position: relative;
  width: 400px;
  height: 400px;
  background-color: red;
}

.wrapper {
  position: relative;
  background-color: green;
  width: 200px;
  height: 200px;
  z-index: 2;
}

.arrow {
  top: 0;
  left: 0;
  position: absolute;
  background-color: yellow;
  width: 50px;
  height: 200px;
  z-index: 3;
}

.background {
  top: 0;
  left: 0;
  position: absolute;
  background-color: blue;
  width: 100px;
  height: 200px;
  z-index: 1;
}
<div class="container">
  <div class="wrapper">
    <div class="arrow"></div> 
  </div>
  <div class="background"></div>
</div>
Kaddath
  • 5,933
  • 1
  • 9
  • 23