简体   繁体   中英

z-index weird behavior?

Given the example below

 function clickme() { console.log(' button been clicked') }
 .d1, .d2 { border: 1px solid red; z-index: -99; opacity: .5; position: relative; } .d2>button { transform: translateY(50px); }
 <div class="d1"> <button onclick="clickme();">Click Me</button> </div> <br> <div class="d2"> <button onclick="clickme();">Click Me</button> </div>

Why when the button moves outside it's parent, it become clickable ?

EDIT:

I used transform: translateY(50px); to move the button, however we can also use position:relative;top:50px; to move the button yet the problem still remains.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM