The natural CSS solution is to:
- Make sure, that "dialogbox" gets a stacking context. This can be done by
- setting
z-index
to something else than auto
,
- and additionally
position
to either relative
, absolute
or fixed
.
- Then add your popup as a child to "dialogbox". If it isn't yet, you can always move it in the DOM.
In that case, your popup doesn't need a z-index
at all. This completely avoids the "z-index hell".
Example:
<!doctype html>
<html>
<head>
<style type="text/css">
#dialogbox {
width: 400px; height: 300px;
top: 0; left: 0;
background-color: red;
}
#popup {
width: 500px; height: 200px;
top: 0; left: 0;
background-color: green;
}
</style>
</head>
<body>
<div id="dialogbox" style="z-index: 100; position: absolute;">
<div>
<div id="widgetThatCausesThePopup" >
<button>Show popup</button>
</div>
</div>
<div id="popup" style="position: absolute;">
<!-- Empty divs cause really weird problems.
Always make sure, that your divs aren't empty! -->
</div>
</div>
</body>
</html>
The stacking context even allows you to use z-indexes relative to the context, if you need them (note, that the child order doesn't matter, and the z-indexes don't have to be larger than 100):
<div id="dialogbox" style="z-index: 100; position: absolute;">
<div id="popup" style="position: absolute; z-index: 2;">
<!-- Empty divs cause really weird problems.
Always make sure, that your divs aren't empty! -->
</div>
<div>
<div id="widgetThatCausesThePopup" style="position: absolute; z-index: 1;">
<button>Show popup</button>
</div>
</div>
</div>