Here you are facing a hidden issue and translate/opacity has nothing to do here. When using negative z-index
it's like you made your elements to be behind the body
(since this one has a z-index
set to auto
). Then the body
height is defined by its in-flow content (both divs) and using translate simply made the element to be placed below the body thus we can reach it and click it.
let's add some border/background to better see the issue:
function clickme() {
console.log(' button been clicked')
}
.d1,
.d2 {
border: 1px solid red;
z-index:-1;
position: relative;
}
.d2>button {
transform: translateY(50px);
}
body {
background:rgba(255,0,0,0.5);
border:2px solid;
}
html {
background:blue;
}
<div class="d1">
<button onclick="clickme();">Click Me</button>
</div>
<br>
<div class="d2">
<button onclick="clickme();">Click Me</button>
</div>
The body
is the red square, all your element are behind it and the button is moved to the bottom and no more covered by the body. The same will also happen if you move your button using other properties without changing the body
height.
If you add some height to the body, translate won't change anything as the button will kept behind the body
function clickme() {
console.log(' button been clicked')
}
.d1,
.d2 {
border: 1px solid red;
z-index: -1;
position: relative;
}
.d2>button {
transform: translateY(50px);
}
body {
height:100vh;
}
<div class="d1">
<button onclick="clickme();">Click Me</button>
</div>
<br>
<div class="d2">
<button onclick="clickme();">Click Me</button>
</div>