MauriceNino
MauriceNino

Reputation: 6747

How to place the box shadow of sibling elements behind both?

I have a flex container with multiple children, which all have separate box-shadows. They unfortunately overlap each other, even though they have the same z-index.

Is there anything I can do about this?

#container {
  display: flex;
  gap: 10px;
  width: 300px;
  height: 100px;
}

.item {
  flex: 1 0 0;
  border: 1px solid red;
  box-shadow: 0px 0px 30px 20px rgba(0,0,0,1);
  background-color: white;
  
  position: relative;
  z-index: 1;
}
<div id="container">
  <div class="item"></div>
  <div class="item"></div>
</div>

Note: The items should have separate shadows, so placing the shadow on the container won't work.

Upvotes: 0

Views: 64

Answers (1)

MauriceNino
MauriceNino

Reputation: 6747

You need to remove the z-index from the actual element and add a :before pseudo-element, where the actual shadow and z-index: -1 will be applied.

#container {
  display: flex;
  gap: 10px;
  width: 300px;
  height: 100px;
}

.item {
  flex: 1 0 0;
  border: 1px solid red;
  background-color: white;
  
  position: relative;
  z-index: auto; /* <- needs to be unset, or auto */
}

/* add shadow to :before */
.item:before {
  content: '';
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  box-shadow: 0px 0px 30px 20px rgba(0,0,0,1);
  z-index: -1;
}
<div id="container">
  <div class="item"></div>
  <div class="item"></div>
</div>

Upvotes: 1

Related Questions