Home > database >  How to render subchild above parent overlay
How to render subchild above parent overlay

Time:12-04

I want a gray overlay above all children except for the selected one. Given the following structure:

<div >

  <!-- I have this subparent which is absolute. I cannot remove it... -->
  <div >
    <div >

      <!-- This child I want to be above the OVERLAY, aka not greyed out -->
      <div >child</div>

      <div >child</div>
      <div >child</div>
    </div>
  </div>

  
  <!--   This component is underneat subParent in the tree structure -->    
  <div ></div>
  
</div>

Here's an exact fiddle. Maybe, I could use a pseudo-element instead?

PS: I updated the children to be a bit more nested to align with my actual code.

CodePudding user response:

You can take the reference from below code. I have altered the CSS a bit. I have added z-index wherever required you can optimise that. Also, removed position: absolute; from subParent1 and added top: 0; left: 0; on the grayOverlay. You can optimise it or change it as per you preference.

.parent {
  width: 300px;
  height: 300px;
  position: relative;
  background-color: gray;
}

.grayOverlay {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  background-color: rgb(107 114 128 / 0.8);
  z-index: 11000;
}

.subParent1 {
  display: flex;
  flex-direction: column;
  width: 100%;
  z-index: 12000;
}

.child {
  color: black;
  width: 50px;
  height: 20px;
  background-color: white;
  margin: 10px;
  z-index: 10000;
}

.childIWantOverOverlay {
  background-color: red;
  z-index: 12000;
}
<div >

  <div >
    <div >child</div>
    <div >child</div>
    <div >child</div>
  </div>

  <!--   This component is underneat subParent in the tree structure -->
  <div ></div>

</div>

CodePudding user response:

UPDATE 2

Perhaps also consider use a pseudo-element for this, if it is acceptable in the actual use case.

This approach is more isolated, so it might be less likely to have conflict with other existing elements in the actual project.

Example with pseudo-element:

const btn = document.querySelector("button");
const divs = document.querySelectorAll("div.child");

let i = 0;

btn.addEventListener("click", () => {
  divs[i].classList.toggle("selected");
  if (i < 2) {
    divs[i   1].classList.toggle("selected")
    i  ;
    return;
  };
  if (i >= 2) {
    i = 0;
    divs[i].classList.toggle("selected");
  }

});
/* Can Change */

.parent {
  width: 300px;
  height: 300px;
  position: relative;
}


/*            
  •  Tags:  
  • css
  • Related