Let’s say I have a layout like this:
<body>
<main class="main">
<div class="aside-section">first</div>
<div class="section">second</div>
</main>
</body>
And css like this:
.main {
display: flex;
padding: 30px;
background: rgba(0, 0, 0, 0.8);
position: relative;
z-index: 10;
}
.aside-section {
width: 50%;
padding-left: 150px;
height: 90vh;
position: fixed;
background: green;
}
.section {
margin-left: 50%;
width: 50%;
height: 90vh;
background-color: yellow;
}
main
z-index is not working and aside-section
and section
appear on top of it. I want main
to be on top of all elements to make a modal mask. I can’t figure out how to solve the issue and why it is happening in the first place. How can I fix it?
2
Answers
The problem you’re experiencing arises from the position: fixed rule in the .aside-section class. A fixed-positioned element is taken out of the normal document flow and positioned relative to the viewport. As such, it creates a new stacking context, which means that its z-index and that of its children are considered separately from the stacking context of its parent.
Now, the stacking should be .section at the bottom, .aside-section above it, and .main on the very top, due to their respective z-index values.
Also, ensure that there are no parent elements of .main with a position value other than static and a z-index set, as these can create a new stacking context that can interfere with the desired stacking order.
I’ve created a code snippet to demonstrate the code you’ve pasted.
I don’t really get what you’re trying to achieve, but I can say that
position:fixed
is a potentially dangerous thing to use, so I would make sure that you really really want it and understand it before deciding to keep it.