简体   繁体   中英

Css modal box z index doesnt work

I'm trying to build simple modal and for some reason the z-index doesn't work. what is the problem here?

 document.addEventListener("DOMContentLoaded", function() { var aTag = document.querySelector('.img-box'); aTag.addEventListener('click', function(e) { e.preventDefault(); document.body.classList.add('overlay'); var img = document.createElement('img'), modalBox = document.getElementById('modal-box') img.src = this.href; modalBox.appendChild(img); }) }); 
 .overlay { position: fixed; top: 0; left: 0; background: #000; opacity: 0.4; width: 100%; height: 100%; } #modal-box { z-index: 1; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } #modal-box img { max-width: 100%; } 
 <a href="http://placehold.it/400x200" class="img-box"> <img src="http://placehold.it/100x100" /> </a> <div id="modal-box"></div> 

Alternate demo: http://codepen.io/phpnetanel/pen/qEjJbo

The problem is that you add the .overlay class to the document body. The rest of the content is held in the document body and thus it stays on top. Create a new overlay div and add it to the body and apply the .overlay class to it.

Here's a working example: http://codepen.io/anon/pen/EaXdKw

You are applying the .overlay class to the body. This will not create an overlay above the content like you are expecting. You need to create another element.

This should do what you want.

您只需要在#modal-box中将位置更改为相对位置即可代替绝对位置,即可使用

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