使用纯CSS在弹出框下面的蒙版效果

时间:2013-05-10 06:36:24

标签: html css css3

我通过在div中添加一个类turnIntoOverlay,将我的网页上的任何div转换为弹出框。 (见JSFiddle

.turnIntoOverlay {
    position: fixed;
    background-color: white;
    top: 60px;
    max-width: 680px;
    z-index: 80;
    border: 6px solid #BBB;
    box-shadow: 0 1px 10px rgba(0, 0, 0, 0.5);
    max-height: 800px;
    overflow: auto;
    padding:10px;
}

现在,当弹出窗口显示时,我还想创建一个遮罩,将褪色层(或遮罩)放在弹出框下方显示的其他页面元素上。为了创建这个掩码,我使用psuedo选择器使用纯css方法,以便在弹出框(turnIntoOverlay元素)可见时显示/隐藏掩码。我添加了以下css:

.turnIntoOverlay:after {
    content: "";
    background-color: whitesmoke;
    position: fixed;
    width: 100%;
    height: 100%;
    z-index: -1;
    opacity: 0.5;
    top: 0;
    left: 0;
}

一切正常,只有当我保持z-index低于弹出窗口时,弹出窗口上也会出现掩码。另外令我惊讶的是,它只适用于z-index=-1。 你能否建议如何纠正这个问题?

请参见JSFiddle此处

3 个答案:

答案 0 :(得分:5)

问题是stacking context:after内容不能低于它的父级,除非父级不在堆叠上下文中,在您的情况下是不可选的。 z-index: -1有效,因为它是一种特殊情况,优先于父母内容。这就是为什么它不影响文本,但影响背景和边框。请参阅Stacking Contexts上的列表。你的:after { z-index: -1 }是nr。列表中有2个。

您唯一的选择是使用额外的包装器:

<div class="turnIntoOverlay"><div>this div is convertible to pop up!<input/></div></div>

.turnIntoOverlay的当前样式移至.turnIntoOverlay > div,并将叠加层应用于外部div并使用正z-index

.turnIntoOverlay:after {
    z-index: 1;
}

Here is a demo

不幸的是IE8及以下版本都有错误。他们也不知道opacity并且使用-ms-filter对没有像伪类:before:after这样的布局的元素不起作用。


当然,如果你还是使用了一个额外的包装器,你可以给另一个包装器background-color。那时不需要:after

.turnIntoOverlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: skyblue; /* for old browsers */
    background-color: rgba(135, 206, 235, 0.4);
}

与伪类方法相比,这包括IE8及更低版本的一些修复。通过使用应用于IE的透明png可以做得更好。有了它,它在每个浏览器中看起来都是一样的(我会说IE6之后)。

Here is a demo

答案 1 :(得分:2)

我的解决方案是使用:before:after来解决您的问题:

.turnIntoOverlay {
    position: fixed;
    background-color: white;
    top: 60px;
    max-width: 680px;
    border: 6px solid #BBB;
    box-shadow: 0 1px 10px rgba(0, 0, 0, 0.5);
    max-height: 800px;
    overflow: auto;
    padding:10px;
    z-index: 80;
}

.turnIntoOverlay:before {
    content: "";
    background-color: skyblue;
    position: fixed;
    width: 100%;
    height: 100%;
    z-index: -1;
    opacity: 0.4;
    top: 0;
    left: 0;
}

.turnIntoOverlay:after{
    position: absolute; 
    width: 100%;
    height: 100%;
    top: 0; 
    left: 0;
    background-color: white;
    z-index: -1;
    content: "";
}

<强> JSFiddle

答案 2 :(得分:0)

我从position: fixed取出了.turnIntoOverlay,现在可以了。

相关问题