Jerald
Jerald

Reputation: 4048

Click event on element with negative z-index

I have a parent element with partially transparent background. There is a child element inside of this element. And I need to show child element in the background of parent element, so I set z-index: -1 to child element.

Here is a codepen example: https://codepen.io/anon/pen/xpVbPa

The gray square is a child element. I need to handle click on it. How to do it? I tried to set pointer events: none on parent element, it does not work.

Upvotes: 3

Views: 2600

Answers (3)

Ajeesh KH
Ajeesh KH

Reputation: 340

Update your CSS. Set background to child's div :after

.child:after{
  width: 150px;
  height: 150px;
  background-color: gray;
  position: absolute;
  cursor: pointer;
  content:"";
  z-index: -1;
}
.child {
  width: 150px;
  height: 150px;
}

Upvotes: 0

tao
tao

Reputation: 90188

The principle in solving this type of problem is not having the background on the parent of .child, but on a sibling:

function childClick() {
  alert('click!');
}
.parent {
  position:relative;
}
.frontground {
  width: 200px;
  height: 200px;
  border: 1px solid black;
  padding: 50px;
  pointer-events: none;
  position: relative;
  background: url(https://image.ibb.co/fAYr5R/585e4ad1cb11b227491c3391.png)
}
.child {
  width: 150px;
  height: 150px;
  background-color: gray;
  cursor: pointer;
  position: absolute;
  margin: 50px;
}
<div class="parent">
  <div class="child" onclick="childClick()"></div>
  <div class="frontground"></div>
</div>

In your case, the sibling can actually be a pseudo-element, but that might not always be possible.

Upvotes: 1

Chris Happy
Chris Happy

Reputation: 7295

Use a pseudo element with a background and add pointer-events: none to it.

Codepen

function childClick() {
  alert('click!');
}
.parent {
  width: 200px;
  height: 200px;
  border: 1px solid black;
  padding: 50px;
  position: relative;
}

.parent:after {
  content: '';
  background: url(https://image.ibb.co/fAYr5R/585e4ad1cb11b227491c3391.png);
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: block;
  pointer-events: none;
}

.child {
  width: 150px;
  height: 150px;
  background-color: gray;
  cursor: pointer;
  position: absolute;
}
<div class="parent">
  <div class="child" onclick="childClick()"></div>
</div>

Upvotes: 3

Related Questions