Reputation: 38032
I'm trying to create a very simple modal in CSS and wanted to use a single DOM element for the 'vignette' and the main content. Thus far I have:
<div class="modal"></div>
.modal {
position: fixed;
top: 20%;
left: 50%;
right: 50%;
width: 620px;
margin: 0 -320px;
height: 540px;
background: $white;
z-index: 4000;
}
/* Vignette */
.modal:before {
content: "";
position: fixed;
top: 0;
left: 0;
bottom: 0;
right: 0;
width: 100%;
height: 100%;
background: $black;
z-index: 2000
}
Unfortunately this is leading to the vignette being displayed over top of the modal (not behind it as desired). How can it be forced underneath without creating a new div for it?
Upvotes: 7
Views: 9221
Reputation: 13546
It's about so called stacking context. Each positioned element establishes the stacking context for its positioned descendants, so such descendants with positive z-index appear above their parent, regardless z-index of the parent itself.
To move the descendant below the parent, you can use negative z-index (e.g. z-index: -1). But even with negative z-index, the positioned child can't be moved below the background of the parent element (kind of counter-intuitive part of standard, but so it works). That's why you will need two pseudo-elements — one for the vignette and one for the background for the modal itself.
Example: http://jsbin.com/ajarey/5/edit
Upvotes: 5
Reputation: 106008
there's one trick you could use to blakken all page from one single element:
.modal {
/* your css */
outline: solid 800px black;
}
or
.modal {
/* your css */
box-shadow: 0 0 0 800px black;
}
so it doesnt stand underneath, but all around.
Upvotes: 6
Reputation: 751
You cannot do this, at least not with cross-browser code. Pseudo-elements as :before and :after are on another stack started from the parent element.
This is stated in the CSS specification files:
The :before and :after pseudo-elements elements interact with other boxes, such as run-in boxes, as if they were real elements inserted just inside their associated element
http://www.w3.org/TR/CSS21/generate.html#before-after-content
Upvotes: 5