带有伪元素的CSS叠加层 [英] CSS Overlay with pseudo element
问题描述
如何创建带有伪元素的CSS覆盖?
How do I create a CSS overlay with an pseudo element?
.modal {
position:fixed;
top:100px;
margin-left: auto;
margin-right: auto;
left:0;
right:0;
width:500px;
display:none;
border:2px solid #736D61;
background:#fff;
padding:10px;
}
.modal:after {
position:fixed;
top:0px;
left:0px;
width:100%;
height:100%;
background:rgba(0,0,0,0.5);
}
我已经尝试过了,但是没有用.
I have tried this but it's not working.
推荐答案
它可能不起作用,因为如果省略 content
值,则不会生成伪元素.默认的 content
值为 none
,这很可能就是您看不到伪元素的原因.因此,您需要为 content
属性指定除 none
之外的其他值:
It probably isn't working because the pseudo-element isn't generated if the content
value is omitted. The default content
value is none
, which is likely why you aren't seeing the pseudo element. Therefore you need to specify a value other than none
for the content
property:
.modal:after {
content: '';
position: fixed;
top: 0px;
left: 0px;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
}
值得一提的是,由于伪元素本质上是作为子元素添加的,因此,由于建立了堆栈上下文,因此它将位于 .modal
元素上方.要解决此问题,您可以在 .modal
元素的父元素中添加:before
伪元素,如下所示:
It's also worth mentioning that since a pseudo element is essentially added as a child element, it will be positioned above the .modal
element since a stacking context is established. To work around that, you could add a :before
pseudo element to the .modal
element's parent like this:
.modal {
position: fixed;
top: 100px;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
width: 500px;
border: 2px solid #736D61;
background: #fff;
padding: 10px;
}
.modal-overlay:before {
content: '';
position: fixed;
top: 0px;
left: 0px;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
}
<div class="modal-overlay">
<div class="modal">MODAL</div>
</div>
这篇关于带有伪元素的CSS叠加层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!