CSS: Inset shadow by parenting div over iframe

2019-05-10 08:29发布

问题:

I'd like to achieve an effect of a shadowed iframe element by its parenting div element.

HTML

<div> <iframe width="560" height="315" src="//www.youtube.com/embed/zdOmNiXvM3w?rel=0" frameborder="0" allowfullscreen></iframe> </div>

CSS

div {
    box-shadow: 
    inset 0px 11px 8px -10px black,
    inset 0px -11px 8px -10px black;
}

The above is what I've got so far, but the iframe appears to take priority regardless of using z-index in CSS. I've used a Youtube iframe in this example, but this solution also needs to work with standard iframes, such as one to google. Ideally using only CSS/HTML.

回答1:

The iframe will always be above the box-shadow of its parent. To counter this issue, you can assign the box-shadow to a pseudo-element positioned absolutely within the parent element, and make it non-responsive to pointer events:

div {
    position: relative;
}
div iframe {
    display: block;
    position: relative;
    z-index: 1;
}
div::before {
    background-color: rgba(255,255,255,.5); // Added only to show overlay, can be removed
    content: '';
    position: absolute;
    z-index: 2;
    box-shadow: inset 0px 11px 8px -10px black, inset 0px -11px 8px -10px black;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    pointer-events: none;
}

I've added the slightly transparent white background to show the overlay. You can always remove it. See proof-of-concept fiddle here: http://jsfiddle.net/teddyrised/uva5zkrg/