[英]Css modal box z index doesnt work
I'm trying to build simple modal and for some reason the z-index
doesn't work. 我正在尝试构建简单的模态,并且由于某种原因z-index
不起作用。 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 备用演示: http : //codepen.io/phpnetanel/pen/qEjJbo
The problem is that you add the .overlay
class to the document body. 问题是您将.overlay
类添加到文档主体。 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. 创建一个新的overlay div并将其添加到主体,然后将.overlay
类应用于它。
Here's a working example: http://codepen.io/anon/pen/EaXdKw 这是一个工作示例: http : //codepen.io/anon/pen/EaXdKw
您只需要在#modal-box中将位置更改为相对位置即可代替绝对位置,即可使用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.