Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine z-indexes of nested elements of two different parents and their stacking context

Tags:

html

css

z-index

I have been searching the web for a solution to my problem. All the documentation I have found so far hints that what I want to achieve is not possible. Well, is it so? Describing the problem in words:

  • I have several entities where each entity has a semi-transparent overlay attached to it.
  • The overlay must be rendered behind all the other entities including the parent entity.
  • I have provided an example in the image below.

Now, the challenge part is these 2 simple rules:

  • Parent Entity A and Parent Entity B must be siblings to each other
  • Overlay A must be a child of Parent A, and same goes for Overlay B

Can we trick the stacking context to achieve this visual below?

A JS solution may be welcome as well, but know that I'm using React and I cannot do DOM manipulation directly, and the parent & sibling relation is a must.

Here's a JS fiddle playground to help you experiment on this. Fiddle is not the solution, it has overlays as siblings to the parent entities.

Try to nest the overlays inside their parents.

example

like image 890
batilc Avatar asked Sep 13 '25 21:09

batilc


1 Answers

You can remove z-index from the entities to prevent them from creating stacking contexts, and use a negative z-index on the overlays to place them behind.

In the following code I define the overlays via pseudo-elements because of semantics, but with real child elements it would would work exactly the same.

#entities-wrapper {
  position: relative; /* Only the wrapper (and overlays) establish */
  z-index: 0;         /* stacking contexts, entities don't.        */
}
.entity, .entity::after {
  position: absolute;
}
.entity { /* Do not use z-index here */
  width: 100px;
  height: 100px;
  text-align: center;
  font-size: 16px;
  line-height: 100px;
}
.entity::after { /* This is the overlay */
  content: '';
  display: block;
  left: 50%;
  top: 50%;
  margin-left: -150px;
  margin-top: -150px;
  width: 300px;
  height: 300px;
  background: rgba(0,0,0,0.25);
  border-radius: 150px;
  z-index: -1; /* Behind the entities */
}
#a {
  background: red;
  top: 150px;
  left: 200px;
}
#b {
  background: yellow;
  top: 150px;
  left: 350px;
}
<div id="entities-wrapper">
  <div id="a" class="entity">parent entity A</div>
  <div id="b" class="entity">parent entity B</div>
</div>
like image 91
Oriol Avatar answered Sep 15 '25 14:09

Oriol